I've been struggling to get my nested form to save the users' inputs. The "outer" form saves the information perfectly. The "inner", or nested, one creates a new object, and passes hidden-field informations, but all other values are "nil".
Each order has one or more date_orders, and you should be able to create the first one through this form.
My code follows. Please help me spot anything that might be causing that. I've browsed StackOverflow extensively.
orders_controller.rb
class OrdersController < ApplicationController
def new
@order = Order.new
@order.date_orders.build
end
def create
@order = Order.new(order_params)
@order.date_orders.build
if @order.save
flash[:success] = "Success"
redirect_to current_user
else
render 'new'
end
end
def order_params
params.require(:order).permit(
:user_id, :description, date_order_attributes:
[:id, :order_date, :time_start, :time_end, :order_id])
end
end
order.rb
class Order < ActiveRecord::Base
has_many :date_orders, :dependent => :destroy
accepts_nested_attributes_for :date_orders
end
date_order.rb
class DateOrder < ActiveRecord::Base
belongs_to :order
end
routes.rb --> date_orders is not mentioned in the routes. Is that a problem?
orders/new.html.erb
<%= form_for(@order, :html => {:multipart => true}) do |f| %>
<!-- form_for fields FIELDS -->
<%= fields_for :date_orders do |builder| %>
<%= builder.hidden_field :order_id, :value => @order.id %> <- THIS WORKS
<%= builder.label :date %>
<%= builder.date_field :order_date %>
<%= builder.label :starting_time %>
<%= builder.time_field :time_start %>
<%= builder.label :ending_time %>
<%= builder.time_field :time_end %>
<% end %>
<%= f.submit "Request", class: "btn" %>
<% end %>
EDIT: example of a hash that is created:
<DateOrder id: 9, order_date: nil, time_start: nil, time_end: nil, order_id: 29, created_at: "2016-04-29 22:43:18", updated_at: "2016-04-29 22:43:18">enter code here`
@order.date_orders.buildin the#createaction is unnecessary. It builds a new object from scratch, which is not what you want - you only want to save the user input. Can you paste here an example for theparamshash the#createaction receives after submitting in the UI input that is not working properly for you?permit. It should bedate_orders_attributesin plural. Please look at the server lograils skeeps spitting out - all non permitted attributes should get a warning. Make sure you don't have any.paramshash the controller action#createreceive, not a newly created date order object.