Forum: Ruby on Rails belongs_to cache

02e1c7c94b08c27fc5e85d064cdf4c16?d=identicon&s=25 Dmitri K. (dmitri_k)
on 2011-04-15 20:08
(Received via mailing list)
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?
81b61875e41eaa58887543635d556fca?d=identicon&s=25 Frederick Cheung (Guest)
on 2011-04-17 09:32
(Received via mailing list)
On Apr 15, 7:07pm, koulikoff <koulik...@gmail.com> 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
Please log in before posting. Registration is free and takes only a minute.
Existing account

NEW: Do you have a Google/GoogleMail, Yahoo or Facebook account? No registration required!
Log in with Google account | Log in with Yahoo account | Log in with Facebook account
No account? Register here.