How to update child object in a nested form in Rails

Go To


I have a nested form Parent, which accepts attribute for Child. In my controller#new, I do

  @parent =

and the nested form works fine

For updating Parent and Child, in my controller#edit, I have

  @parent = Parent.find(params[:id]) unless not @parent.childs.empty?

Now, if I go to edit page, only fields for parent will show up. My question is: How to I let Rails know that I want the form for Parent and Child, and not just for Parent?

Thank you

2012-04-04 01:28
by AdamNYC


Use the fields_for helper - it will almost do everything for you.

<%= form_for @parent do |f| %>
  <%= f.text_field :name %>
  <%= f.fields_for :children, @parent.children do |c| %>
    <%= c.text_field :name %>
  <% end %>
<% end %>
2012-04-04 02:56
by klump