# ActiveRecord gotcha with references?

**URL:** <https://www.ruby-forum.com/t/activerecord-gotcha-with-references/111257>\
**Category:** Rails\
**Created:** [August 4, 2007, 2:21pm UTC](https://www.ruby-forum.com/t/activerecord-gotcha-with-references/111257 "2007-08-04T14:21:20Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![pearl8](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/p/439d5e/32.png) [@pearl8](https://www.ruby-forum.com/u/pearl8)\
**Post date:** [August 4, 2007, 2:21pm UTC](https://www.ruby-forum.com/t/activerecord-gotcha-with-references/111257/1 "2007-08-04T14:21:20Z")

</div>

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!

---

<div class="post-metadata">

**Author:** ![pearl8](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/p/439d5e/32.png) [@pearl8](https://www.ruby-forum.com/u/pearl8)\
**Post date:** [August 6, 2007, 6:35am UTC](https://www.ruby-forum.com/t/activerecord-gotcha-with-references/111257/2 "2007-08-06T06:35:14Z")

</div>

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 B. ([http://ola-bini.blogspot.com](http://ola-bini.blogspot.com))  
JRuby Core Developer
