ruby-on-railsnested-attributesupdate-attributes

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.


Solution

  • I solved this problem by adding the update_only option:

    accepts_nested_attributes_for :profile, update_only: true
    

    Now a new profile is only created if one does not already exist.