我在使用嵌套属性创建多个模型对象时遇到问题。形式.erb我有:
<%= f.fields_for :comments do |c| %>
<%= c.text_field :text %>
<% end %>
生成如下所示的输入字段:
<input type="text" name="ad[comments_attributes][0][text]" />
<input type="text" name="ad[comments_attributes][1][text]" />
<input type="text" name="ad[comments_attributes][2][text]" />
当我真正想要的是它看起来像这样:
<input type="text" name="ad[comments_attributes][][text]" />
<input type="text" name="ad[comments_attributes][][text]" />
<input type="text" name="ad[comments_attributes][][text]" />
使用表单助手,如何让表单像第二个例子中那样创建一个哈希数组,而不是像第一个那样使用哈希哈希?
答案 0 :(得分:7)
您可以将text_field_tag用于此特定类型要求。 此FormTagHelper提供了许多创建表单标记的方法,这些方法不依赖于分配给模板的Active Record对象,如FormHelper。而是手动提供名称和值。
如果你给他们所有相同的名字,并将[]追加到最后,如下所示:
<%= text_field_tag "ad[comments_attributes][][text]" %>
<%= text_field_tag "ad[comments_attributes][][text]" %>
<%= text_field_tag "ad[comments_attributes][][text]" %>
您可以从控制器访问这些:
comments_attributes = params [:ad] [:comments_attributes]#这是一个 阵列
上面的field_tag html输出如下所示:
<input type="text" name="ad[comments_attributes][][text]" />
<input type="text" name="ad[comments_attributes][][text]" />
<input type="text" name="ad[comments_attributes][][text]" />
如果在方括号之间输入值,则rails会将其视为哈希:
<%= text_field_tag "ad[comments_attributes][1][text]" %>
<%= text_field_tag "ad[comments_attributes][2][text]" %>
<%= text_field_tag "ad[comments_attributes][3][text]" %>
将被控制器解释为具有键“1”,“2”和“3”的散列。 我希望我能正确理解你需要的东西。
由于