ruby-on-rails – Rails嵌套属性数组
发布时间:2020-12-17 02:45:26 所属栏目:百科 来源:网络整理
导读:我在使用嵌套属性创建多个模型对象时遇到问题.形式.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[
我在使用嵌套属性创建多个模型对象时遇到问题.形式.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]" /> 使用表单助手,如何使表单创建像第二个示例中的哈希数组,而不是像第一个中那样使用哈希哈希? 解决方法
您可以将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]" %> 您可以从控制器访问这些:
上面的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”的散列. 谢谢 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |