Habtm and counter_cache

Hi,

I’ve a set of two models in habtm relationship. However,
since :counter_cache can only be used on belongs_to method, how can I
implement the counter cache on habtm models?

I have tried with after_add and after_remove callbacks, but I don’t
know quite how to code the method for updating.

I created this method:

def update_count
self.posts_count = self.posts.length
end

into:

class Category < ActiveRecord::Base
has_and_belongs_to_many :posts,
:after_add => :update_count,
:after_remove => :update_count
end

However, the method doesn’t work (or I wouldn’t be posting here, would
I?)… I would appreciate any help, or maybe a tip on where to find
relevant information.

Thanks.

Branko

Solved it a bit differently. :slight_smile:

D’oh! after_create in Post model was the correct answer…

I’ve documented it for people who might be looking for this.

http://eyedeal.team88.org/node/104