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

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Kad K. (Guest)
on 2007-02-14 20: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
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
Andrew C. Greenberg (Guest)
on 2007-03-05 21: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.