Belongs_to cache

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?

On Apr 15, 7:07pm, koulikoff [email protected] 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