[英]How to update child object in a nested form in Rails
I have a nested form Parent, which accepts attribute for Child.我有一个嵌套的 Parent 表单,它接受 Child 的属性。 In my controller#new, I do
在我的控制器#new 中,我做
@parent = Parent.new
@parent.childs.build
and the nested form works fine嵌套形式工作正常
For updating Parent and Child, in my controller#edit, I have为了更新父子,在我的控制器#edit 中,我有
@parent = Parent.find(params[:id])
@parent.childs.build unless not @parent.childs.empty?
Now, if I go to edit page, only fields for parent will show up.现在,如果我 go 编辑页面,只会显示父字段。 My question is: How to I let Rails know that I want the form for Parent and Child, and not just for Parent?
我的问题是:如何让 Rails 知道我想要父子表单,而不仅仅是父表单?
Thank you谢谢
Use the fields_for
helper - it will almost do everything for you.使用
fields_for
助手 - 它几乎可以为您做所有事情。
<%= form_for @parent do |f| %>
<%= f.text_field :name %>
<%= f.fields_for :children, @parent.children do |c| %>
<%= c.text_field :name %>
<% end %>
<% end %>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.