I am trying to get hold of the rails counter caching function, but cannot fully understand it.
Say we have 3 models
Abc
A belongs to B or C depending on the key_type and key_id fields. key_type indicates whether A belongs to B or C, so if key_type = "B", then the entry belongs to B, otherwise it belongs to C.
In my a.rb model, I defined the following associations:
belongs_to :b, :counter_cache => true, :foreign_key => "key_id" belongs_to :c, :counter_cache => true, :foreign_key => "key_id"
and
in model b and c files
has_many :as , :conditions => {:key_type => "B"} has_many :as , :conditions => {:key_type => "C"}
Both models B and C have an as_count column
The problem is that every time the object a is created, the count increases in both models b and c.
Any help is appreciated. I initially thought this might 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 that does not help.
thanks
ruby ruby-on-rails ruby-on-rails-plugins
Ishu
source share