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

Posted About 13 years ago. Visible to the public.

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.

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
Henning Koch
Last edit
Over 11 years ago
License
Source code in this card is licensed under the MIT License.
Posted by Henning Koch to makandra dev (2011-03-10 14:43)