Problems with accepts_nested_attributes_for

Hopefully someone can help. I have the following models

class Parent < ActiveRecord::Base

schema id int, name string

has_many :children
accepts_nested_attributes_for :children
end

class Child < ActiveRecord::Base

schema id int, name string, parent_id int

belongs_to :parent
end

… the following view …

New parent

<% form_for :parent, :url => { :action => :create } do |p| %>
<%= p.text_field :name %>


<% p.fields_for :children do |c| %>
<%= c.text_field :name %>
<% end %>

<%= p.submit ‘Create’ %>

<% end %>

… and a scaffold built parents_controller …

GET /parents/new

GET /parents/new.xml

def new
@parent = Parent.new

respond_to do |format|
  format.html # new.html.erb
  format.xml  { render :xml => @parent }
end

end

POST /parents

POST /parents.xml

def create
@parent = Parent.new(params[:parent])

respond_to do |format|
  if @parent.save
    flash[:notice] = 'Parent was successfully created.'
    format.html { redirect_to(@parent) }
    format.xml  { render :xml => @parent, :status => :created, :location => @parent }
  else
    format.html { render :action => "new" }
    format.xml  { render :xml => @parent.errors, :status => :unprocessable_entity }
  end
end

end

I’m getting this error …

Hi Anthony,

It looks like your form_for line in your view is wrong... try this:
  <% form_for(@parent) do |p| %>

...instead of this:
  <% form_for :parent, :url => { :action => :create } do |p| %>

For some reason the way you called form_for isn't compatible with the
nested attributes feature, and so your form's HTML didn't contain the
proper name for the child field name="parent[children_attributes][0]
[name]". Also, I added a line to your controller to create a single
new child when creating a new parent form; otherwise the child name
field won’t appear:

def new
    @parent = Parent.new
    @parent.children.build

    respond_to do |format|
      format.html # new.html.erb
      format.xml { render :xml => @parent }
    end
  end

It should work exactly the same way with the has_many, :through
association. Hope this helps!

- pat

Cool. Thanks, Pat.

Have just implemented that and it works fine … even with :through.

Nice.

-Ants