# Problem with counter cache in many-to-many relationship

**URL:** <https://www.ruby-forum.com/t/problem-with-counter-cache-in-many-to-many-relationship/222882>\
**Category:** Rails\
**Created:** [September 13, 2012, 3:52pm UTC](https://www.ruby-forum.com/t/problem-with-counter-cache-in-many-to-many-relationship/222882 "2012-09-13T15:52:17Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![aris](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/a/258eb7/32.png) [@aris](https://www.ruby-forum.com/u/aris)\
**Post date:** [September 13, 2012, 3:52pm UTC](https://www.ruby-forum.com/t/problem-with-counter-cache-in-many-to-many-relationship/222882/1 "2012-09-13T15:52:17Z")

</div>

Hi guys,  
I am having trouble getting to counter cache to work properly with a  
many-to-many relationship. What I have done is:

rails g scaffold post title:string body:text  
rails g scaffold tag name:string taggings\_count:integer  
rails g model tagging post\_id:integer tag\_id:integer

Then I created the relationship as shown in my Gist:

> <https://gist.github.com/halfdan/3710093>

The idea is to have an input field when creating a post, where tags can  
be  
entered seperated by comma. The tag\_names method then splits those tags,  
adds new ones and deletes the ones that are now missing.

The counter\_cache is correctly increased when adding a tag to the list.  
However, decreasing the number after a tag removal does not work.

I have done some searching and found several blog articles (e.g.  
[http://whilefalse.net/2011/04/05/rails-3-counter-cache-has\_many-through/](http://whilefalse.net/2011/04/05/rails-3-counter-cache-has_many-through/))  
explaining that this was a bug in Rails 3.0.x that has been addressed in  
edge rails. See the old bug report on lighthouse:  
[https://rails.lighthouseapp.com/projects/8994/tickets/2824-patch-has\_many-through-doesnt-update-counter\_cache-on-join-model-correctly](https://rails.lighthouseapp.com/projects/8994/tickets/2824-patch-has_many-through-doesnt-update-counter_cache-on-join-model-correctly)  
and  
then the fix on Github:  
[Correctly update counter caches on deletion for has\_many :through [#2… · rails/rails@52f09ea · GitHub](https://github.com/rails/rails/commit/52f09eac5b3d297021ef726e04ec19f6011cb302)

Why am I still having this problem, when it was fixed two years ago? Am  
I  
missing something here?

FYI:

# rails -v

Rails 3.2.8

Cheers,  
Fabian
