我有一个嵌套表单,它有一个选择下拉菜单。
当点击“提交”按钮时,如何将所选项目的 ID 传递到提交的属性中?
在我的情况下,这就是我的嵌套表单的部分样子:
=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"
当我点击提交按钮时,终端/控制台显示以下内容正在提交到数据库,但您会注意到menu_id
下拉菜单中的其他两个领域。dishes_attributes
id
name
... "dishes_attributes"=>{"1342759486320"=>{"_destroy"=>"false", "name"=>"Dish 1", "price"=>"32"} ...
从 HTML 源代码中,name
和price
输入字段被分配了以下id
和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"/>
但我的select
下拉列表如下所示:
<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>
在父_form
页面中,调用如下所示,然后调用此部分:
=link_to_add_fields "Add New Dish", f, :dishes
从我的link_to_add_fields
看起来像这样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