ActiveRecord gotcha with references?

I have this situation:

class Employee < ActiveRecord::Base     belongs_to :designation end

class Designation < ActiveRecord::Base end

I do the following at the irb console:

Step 1: Find an employee

emp = Employee.find 3

=> #<Employee:0x35a7d34 @attributes={"designation_id"=>"3", "id"=>"3", "division_id"=>"4"}>

Step 2: Save the designation in a variable des

des = emp.designation

=> #<Designation:0x35a49b8 @attributes={"name"=>"Project Manager", "id"=>"3", "division_id"=>nil}>

des

=> #<Designation:0x35a49b8 @attributes={"name"=>"Project Manager", "id"=>"3", "division_id"=>nil}>

Step 3: Replace the employee's designation

emp.designation = Designation.find 1

=> #<Designation:0x359fa80 @attributes={"name"=>"Trainee", "id"=>"1", "division_id"=>nil}>

Step 4: Notice that the variable des's object id has changed

des

=> #<Designation:0x359fa80 @attributes={"name"=>"Trainee", "id"=>"1", "division_id"=>nil}>

At step 4 i would NOT EXPECT the reference of des to change as des at step 2 had reference to object Designation:0x35a49b8

However if i change emp.designation the variable des automagically changes to refer to the same object that emp.designation is referring to! It's almost like whenever I refer to des, emp.designation seems to be re-evaluated all over again!

Here's a response I got from another forum. hope that helps someone else!

Actually, the object in des isn't really an instance of Designation, but really a transparent proxy that points to it. When you execute emp.designation=, that transparent proxy will point to another reference. That's why it looks like it's changing object reference on a local variable (which you can't do in Ruby without Binding.of_caller)

Cheers

Ola Bini (http://ola-bini.blogspot.com) JRuby Core Developer