I have a nested form that has a select dropdown menu.
How can I pass the selected item’s ID into the attributes that are submitted when the ‘submit’ button is hit?
In my situation, this is what my nested form’s partial looks like:
=select("dish", "menu_id", Menu.all.collect {|r| [ r.name, r.id ] }, {:include_blank => 'Choose a Menu'})
=f.hidden_field :_destroy
=f.text_field :name, placeholder: "Name"
=f.text_field :price, placeholder: "Price"
=link_to "X", '#', :class => "remove_fields"
When I hit the submit button, the Terminal/Console displays that the following are being submitted to the database but you’ll notice that the menu_id from the dropdown menu isn’t part of the dishes_attributes since it doesn’t share the same input id and name as the other two fields.
... "dishes_attributes"=>{"1342759486320"=>{"_destroy"=>"false", "name"=>"Dish 1", "price"=>"32"} ...
From the HTML source code, the name and price input fields get assigned the following id and name:
<input id="side_dish_dishes_attributes_1342759902918_name" name="side_dish[dishes_attributes][1342759902918][name]" placeholder="Name" size="30" type="text"/>
<input id="side_dish_dishes_attributes_1342759902918_price" name="side_dish[dishes_attributes][1342759902918][price]" placeholder="Price" size="30" type="text"/>
But my select dropdown looks like this:
<select id="dish_menu_id" name="dish[menu_id]">
<option value="">Choose a Menu</option>
<option value="1">Menu 1</option>
<option value="2">Menu 2</option>
</select>
In the parent _form page, here’s what the call looks like that then calls this partial:
=link_to_add_fields "Add New Dish", f, :dishes
With the link_to_add_fields looking like this from my helpers/application_helper.rb:
def link_to_add_fields(name, f, association)
new_object = f.object.send(association).klass.new
id = new_object.object_id
fields = f.fields_for(association, new_object, child_index: id) do |builder|
render(association.to_s.singularize + "_fields", f: builder)
end
link_to(name, '#', class: "add_fields", data: {id: id, fields: fields.gsub("\n", "")})
end
Instead of this line
use it with form object
I hope this will sort out your id problem as well as part of dishes attributes