Rails Counter Cache and its implementation

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

+6
ruby ruby-on-rails ruby-on-rails-plugins
source share
2 answers

It seems that polymorphic associations are a way to solve your problem.

Imagine that you have a comment model and two models that you can comment on: Mail and Profile.

In Post and Profile models:

 has_many :comments, :as => :resource 

In the comment model:

 belongs_to :resource, :polymorphic => true, :counter_cache => true 

Remember to add the "comments_count" column in the Profile and Post and voilà models!

+15
source share
+4
source share

All Articles