Read more

Unexpected behavior when changing both an association and its foreign key attribute in ActiveRecord

Henning Koch
March 10, 2011Software engineer at makandra GmbH

When you set both a record's association and that association's foreign key attribute, Rails does not realize you are talking about the same thing. The association change will win in the next save, even if the foreign key attribute was changed after the association.

Illustration online protection

Rails Long Term Support

Rails LTS provides security patches for old versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2)

  • Prevents you from data breaches and liability risks
  • Upgrade at your own pace
  • Works with modern Rubies
Read more Show archive.org snapshot

As an example, assume you have these two models:

class Group < ActiveRecord::Base
  has_many :users
end

class User < ActiveRecord::Base
  validates_presence_of :group_id
  belongs_to :group
end

We will now load a User and change both its group and its group_id:

user = User.find(1)
user.group = Group.find(3)
user.group # returns #<Group id: 3>
user.group_id = 4
user.group_id # returns 4
user.save

After the save, the change to group_id will be lost:

user.group # returns #<Group id: 3>
user.group_id # returns 3
Posted by Henning Koch to makandra dev (2011-03-10 15:43)