【发布时间】:2013-07-11 15:48:14
【问题描述】:
我有一个父模型和一个子模型。我正在尝试制作一个表单来同时创建父级及其关联的子级。
在我的表单中,我有一个“添加”新子级的按钮(父级可以拥有用户定义的多个子级)。单击该按钮时,它会在表单中添加一个 Child 的隐藏字段,并将其 Name 属性设置为某个默认值,该默认值将在最终提交表单时保存。我一直在通过在按钮单击事件的表单中添加hidden_field_tag 来做到这一点:
hidden_field_tag "parent[children_attributes][][name]", "something"
创建:
<input id="children_attributes__name" name="parent[children_attributes][][name]" type="hidden" value="something">
这似乎有效!但我担心空的[]。我不确定它是什么或它为什么起作用,我只是发现它确实如此。使用安全吗?
当我查看使用 fields_for 创建的表单字段时,我看到它为该中间数组/哈希(无论它是什么)设置了一个数字索引,如下所示:
<input id="children_attributes_0_name" name="parent[children_attributes][0][name]" type="text">
很遗憾,我不能使用fields_for,因为我必须在单击“添加”按钮时才添加隐藏字段。
这里的正确方法是什么?
【问题讨论】:
标签: ruby-on-rails forms post nested-attributes ruby-on-rails-4