# Habtm and counter\_cache

**URL:** <https://www.ruby-forum.com/t/habtm-and-counter-cache/130528>\
**Category:** Rails\
**Created:** [February 29, 2008, 2:38am UTC](https://www.ruby-forum.com/t/habtm-and-counter-cache/130528 "2008-02-29T02:38:05Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![foxbunny](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/f/ed655f/32.png) [@foxbunny](https://www.ruby-forum.com/u/foxbunny)\
**Post date:** [February 29, 2008, 2:38am UTC](https://www.ruby-forum.com/t/habtm-and-counter-cache/130528/1 "2008-02-29T02:38:05Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![foxbunny](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/f/ed655f/32.png) [@foxbunny](https://www.ruby-forum.com/u/foxbunny)\
**Post date:** [March 1, 2008, 11:08pm UTC](https://www.ruby-forum.com/t/habtm-and-counter-cache/130528/2 "2008-03-01T23:08:56Z")

</div>

Solved it a bit differently. 🙂

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](http://eyedeal.team88.org/node/104)
