Forum: Ruby on Rails counter_cache doesn't work for me..

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
Ee0293412faca21e4ebf3326ed9d5f8c?d=identicon&s=25 Kad Kerforn (kadoudal)
on 2007-02-14 19:30
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

class Rating < ActiveRecord::Base
  belongs_to :user, :foreign_key => 'user_id'
  belongs_to :proposal, :foreign_key => 'proposal_id', :counter_cache =>


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
Ff5b4846b93008ffb2161805fa00af5f?d=identicon&s=25 Andrew C. Greenberg (Guest)
on 2007-03-05 20:09
(Received via mailing list)
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!)
This topic is locked and can not be replied to.