1

我有一个嵌套表单,它有一个选择下拉菜单。

当点击“提交”按钮时,如何将所选项目的 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_attributesidname

... "dishes_attributes"=>{"1342759486320"=>{"_destroy"=>"false", "name"=>"Dish 1", "price"=>"32"} ...

从 HTML 源代码中,nameprice输入字段被分配了以下idname

<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
4

1 回答 1

2

而不是这条线

=select("dish", "menu_id", Menu.all.collect {|r| [ r.name, r.id ] }, {:include_blank => 'Choose a Menu'})  

与表单对象一起使用

=f.select("menu_id", Menu.all.collect {|r| [ r.name, r.id ] }, {:include_blank => 'Choose a Menu'})

我希望这能解决您的身份问题以及部分菜肴属性

于 2012-07-20T06:47:43.487 回答