# Counter\_cache doesn't work for me

**URL:** <https://www.ruby-forum.com/t/counter-cache-doesnt-work-for-me/85586>\
**Category:** Rails\
**Created:** [February 14, 2007, 7:30pm UTC](https://www.ruby-forum.com/t/counter-cache-doesnt-work-for-me/85586 "2007-02-14T19:30:16Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![kadoudal](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/k/f0a364/32.png) [@kadoudal](https://www.ruby-forum.com/u/kadoudal)\
**Post date:** [February 14, 2007, 7:30pm UTC](https://www.ruby-forum.com/t/counter-cache-doesnt-work-for-me/85586/1 "2007-02-14T19:30:16Z")

</div>

I am trying to use the counter\_cache but it’s not updated…

class Proposal \< ActiveRecord::Base  
has\_many :ratings, :dependent =\> :destroy

(I have defined a ratings\_count column (default value 0) in my proposals  
table)

class Rating \< ActiveRecord::Base  
belongs\_to :user, :foreign\_key =\> ‘user\_id’  
belongs\_to :proposal, :foreign\_key =\> ‘proposal\_id’, :counter\_cache =\>  
true

proposal\_controller

def add\_new\_rating  
…  
@proposal = Proposal.find\_by\_id(params[:id].to\_i)  
@proposal.ratings.create(:user =\> current\_user, :comment =\> @comment,  
:value =\> @notation)  
@ proposal.update\_attribute(:total\_value , @total\_value)

the rating record is correctly created…  
the proposal record total\_value attribute is correctly updated, but the  
counter ‘ratings\_count’ is not incremented

---

<div class="post-metadata">

**Author:** ![kadoudal](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/k/f0a364/32.png) [@kadoudal](https://www.ruby-forum.com/u/kadoudal)\
**Post date:** [March 5, 2007, 8:09pm UTC](https://www.ruby-forum.com/t/counter-cache-doesnt-work-for-me/85586/2 "2007-03-05T20:09:36Z")

</div>

Check the SQL generated in the log. I’m noticing that the memory  
version of the has\_may record is not having its cache value being  
updated, even when a “parent.child.create” is executed in a 1.2.2  
rails. I’ll wager your code is triggering the SQL update of the  
cache counter increment, but that the update without a reload is  
overwriting the counter cache with the pre-creation value.

I’ll wager that the increment SQL was fired off, but that the old  
value of the cache got rewritten during the update. A work-around  
might be to reload the Proposal record before the update (yick!)
