Question

I am trying to start using nested attributes in my rails 4 app. My model is set up like:

class Person < ActiveRecord::Base
  has_many :addresses
  accepts_nested_attributes_for :addresses
end

class Address < ActiveRecord::Base
  belongs_to :person
end

and my view is:

<%= form_for(:person, :url => {:action => 'update', :id => @person.id}) do |f| %>
  <p>
    <%= f.label :name %><br />
    <%= f.text_field :name %>
  </p>
  <%= f.fields_for(:addresses) do |builder| %>
  <p>
    <%= builder.label :street, "Street" %><br />
    <%= builder.text_field(:street) %>
  </p>
  <% end %>
  <p><%= f.submit "Submit" %></p>
<% end %>

Nearly identical to: http://guides.rubyonrails.org/form_helpers.html

Yet my view is not connecting the builder form to my address model. It is simply rendering the form once.

I also noticed that submitting the data does not provide the params hash as:

{
    :person => {
        :name => 'John Doe',
        :addresses_attributes => {
            '0' => {
                :kind  => 'Home',
                :street => '221b Baker Street',
            },
            '1' => {
                :kind => 'Office',
                :street => '31 Spooner Street'
            }
        }
    }
}

But instead like:

{"person"=
  {"name"=>"John Smith", "adresses"=>
    {"street"=>"221 Baker"}
  }
}

Where am I going wrong?

PS - the controller... I have tried it with a new object, and one that already exists and has addresses associated with it.

def nest
  @person = Person.find(48)

  #@person = Person.new
  #4.times { @person.addresses.build }
end
Was it helpful?

Solution

The problem was in the form_for apparently you MUST be using resourceful routing and use form_for like this:

<%= form_for @person do |f| %>

Thanks to @vee for pointing it out!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top