# Belongs\_to cache

**URL:** <https://www.ruby-forum.com/t/belongs-to-cache/205796>\
**Category:** Rails\
**Created:** [April 15, 2011, 8:08pm UTC](https://www.ruby-forum.com/t/belongs-to-cache/205796 "2011-04-15T20:08:51Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![dubstep](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/d/cdc98d/32.png) [@dubstep](https://www.ruby-forum.com/u/dubstep)\
**Post date:** [April 15, 2011, 8:08pm UTC](https://www.ruby-forum.com/t/belongs-to-cache/205796/1 "2011-04-15T20:08:51Z")

</div>

Hello, All!

I’ve met the strange behavior and would like to ask the community if  
this is normal?

class TradingAccount \< ActiveRecord::Base  
belongs\_to :trading\_account\_type  
end

$ rails c  
Loading development environment (Rails 3.0.5)  
irb(main):001:0\> TradingAccountType.all.map(&:id)  
=\> [1, 2]  
irb(main):002:0\> ta = TradingAccount.find 6  
=\> #\<TradingAccount id: 6, client\_id: 8, trading\_account\_type\_id:  
2, …\>  
irb(main):003:0\> ta.trading\_account\_type.id  
=\> 2  
irb(main):004:0\> ta.trading\_account\_type\_id = 1  
=\> 1  
irb(main):005:0\> ta.trading\_account\_type.id  
=\> 2

It means that after the trading\_account\_type\_id change the object is  
not cleared and remains in the cache.  
I think that the change of trading\_account\_type\_id should clear the  
cache and the following call to #trading\_account\_type should load from  
the database the one with id == 1

I’ve met this problem while establishing the validation:

validates\_uniqueness\_of :trading\_account\_type\_id, :scope  
=\> :client\_id,  
:if =\> Proc.new { |ta| ta.trading\_account\_type.singleton rescue  
nil }

that has to be rewritten as:

validates\_uniqueness\_of :trading\_account\_type\_id, :scope  
=\> :client\_id,  
:if =\> Proc.new { |ta|  
tat = ta.trading\_account\_type  
unless !tat || tat.id == ta.trading\_account\_type\_id  
tat = TradingAccountType.find ta.trading\_account\_type\_id  
rescue nil  
end  
tat && tat.singleton?  
}

What would you say?

---

<div class="post-metadata">

**Author:** ![dokondr](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/d/3be4f8/32.png) [@dokondr](https://www.ruby-forum.com/u/dokondr)\
**Post date:** [April 17, 2011, 9:32am UTC](https://www.ruby-forum.com/t/belongs-to-cache/205796/2 "2011-04-17T09:32:12Z")

</div>

On Apr 15, 7:07pm, koulikoff [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid) wrote:

> Loading development environment (Rails 3.0.5)  
> =\> 2
> 
> It means that after the trading\_account\_type\_id change the object is  
> not cleared and remains in the cache.

I vaguely remember a ticket on the rails bug tracker about this. I  
don’t remember what the resolution was.

Fred
