How to update child object in a nested form in Rails

Go To StackoverFlow.com

2

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

  @parent = Parent.new
  @parent.childs.build

and the nested form works fine

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

  @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. 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


4

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