AdamNYC
AdamNYC

Reputation: 20445

How to update child object in a nested form in Rails

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

Upvotes: 2

Views: 4047

Answers (1)

klump
klump

Reputation: 3269

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 %>

Upvotes: 4

Related Questions