Ruby on rails Rails嵌套属性数组

Ruby on rails Rails嵌套属性数组,ruby-on-rails,ruby-on-rails-3,Ruby On Rails,Ruby On Rails 3,使用嵌套属性创建多个模型对象时遇到问题。我有以下表格: <%= 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_att

使用嵌套属性创建多个模型对象时遇到问题。我有以下表格:

<%= 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]" />
<input type="text" name="ad[comments_attributes][][text]" />
<input type="text" name="ad[comments_attributes][][text]" />
<input type="text" name="ad[comments_attributes][][text]" />

当我真正想要的是它看起来像这样:

<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]" />
<input type="text" name="ad[comments_attributes][][text]" />
<input type="text" name="ad[comments_attributes][][text]" />
<input type="text" name="ad[comments_attributes][][text]" />


使用表单帮助程序,如何使表单像第二个示例中那样创建散列数组,而不是像第一个示例中那样创建散列数组?

您可以使用text\u field\u标记来满足此特定类型的要求。 此FormTagHelper提供了许多方法来创建表单标记,这些方法与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]#这是一个 排列

上面的字段标记html输出如下所示:

<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]" />
<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”的散列。 我希望我能正确理解你的需求


谢谢

那会有用的。我们不能为(:comments,:prefix=>'comments\u attributes[])添加一个属性到
f.fields\u中吗