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 UI/UX Design

UI/UX Design by makandra brand

We make sure that your target audience has the best possible experience with your digital product. You get:

  • Design tailored to your audience
  • Proven processes customized to your needs
  • An expert team of experienced designers
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)