Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nested attribute update_attributes uses insert rather than update

I have a user and nested profile class as follows:

class User < ActiveRecord::Base   has_one :profile   attr_accessible :profile_attributes   accepts_nested_attributes_for :profile end  class Profile < ActiveRecord::Base   belongs_to :user   attr_accessible :name end  user = User.find(1) user.profile.id  # => 1 user.update_attributes(profile_attributes: {name: 'some name'}) user.profile.id  # => 2 

I don't understand why rails is throwing away the old profile and creating a new one.

Using

user.profile.update_attributes({name: 'some name'}) 

just updates the current profile as expected. But in that case I'm not taking advantage of accepts_nested_attributes_for

Does anyone know why the update happens this way? I'd prefer not to end up with a database of profile rows not connected to any user.

like image 962
Jason Avatar asked Mar 30 '12 13:03

Jason


2 Answers

For everyone who has the same problem in Rails 4: fields_for already adds the id for your nested forms but you have to permit the :id parameter. I only permitted an :object_name_id parameter and since this does not throw any errors it took me some time until i saw this in the server logs. Hopefully this helps someone wasting less time than me on this :)

like image 192
irruputuncu Avatar answered Sep 23 '22 12:09

irruputuncu


If you check your form, you need to set the id attribute within the nested attribute hash for your Profile object. If the id is not set, ActiveRecord assumes it's a new object.

For example, if you had an ERB form building a set of 'user' parameters with a nested 'profile_attributes' parameter hash for the nested profile within the user, you could include a hidden value for the profile id, like this:

<%= hidden_field "user[profile_attributes][id]", @profile.id %> 
like image 35
Winfield Avatar answered Sep 22 '22 12:09

Winfield