Rails Counter Cache and its implementation

Posted by Ishu on Stack Overflow See other posts from Stack Overflow or by Ishu
Published on 2010-03-19T09:31:39Z Indexed on 2010/03/19 13:11 UTC
Read the original article Hit count: 585

Hello All,

I am trying to get hold of rails counter cache feature but not able to grasp it completely.

Let's say that We have 3 models

A B C

A belongs to B or C depending upon a field key_type and key_id. key_type tells whether A belongs to B or C so if key_type="B" then the record belongs to B otherwise it belongs to C.

In my model a.rb, I have defined following associations:

belongs_to :b, :counter_cache => true, :foreign_key => "key_id"
belongs_to :c, :counter_cache => true, :foreign_key => "key_id"

and

in b and c model files

has_many :as , :conditions => {:key_type => "B"}
has_many :as , :conditions => {:key_type => "C"}

Both B and C Models have a column as as_count

The problem is every time an object of a is created count is increased in the both the models b and c.

Any help is appreciated. Initially i thought that this may work:

belongs_to :b, :counter_cache => true, :foreign_key => "key_id", :conditions => {:key_type => "B"}
belongs_to :c, :counter_cache => true, :foreign_key => "key_id", :conditions => {:key_type => "C"}

But this does not help.

Thanks

© Stack Overflow or respective owner

Related posts about ruby-on-rails

Related posts about ruby