small medium large xlarge

17 Jul 2008, 19:56
Frank (9 posts)

Hi Ryan i just finished watching the first 4 episodes of everyday activerecord. I really enjoyed them and I learned a lot.

I have a question regarding the callbacks episode. Near the end of the episode you modified the callback called clear_movie_average_stars_cache to handle the case where a review is moved from one movie to another. I think I fully understand that part. But what about the reviews_count ? Does that get automatically adjusted when you move a review from one movie to another due to :counter_cache => true ? I was under the impression that :counter_cache => true only changes the count for create and destroy.

  • thanks, Francois
18 Jul 2008, 17:08
Ryan Bates (60 posts)

Good question. The counter_cache does handle the case of moving a review from one movie to another. However it does not do it using callbacks - it is deeper ingrained inside the code itself. Specifically in the BelongsToAssociation#replace method.

03 Feb 2009, 02:53
Frank (9 posts)

I’ve been trying to use the counter_cache on a new project (in Rails 2.2) and here’s what I’m seeing:

I have a City model and a Boardroom model where by a City has_many Boardrooms and Boardrooms belongs_to City, with counter_cache => true

1) Creating a new boardroom successfully increments the boardrooms_count 2) Deleting a boardroom will automatically decrement the boardrooms_count as well 3) updating a boardroom using update_attributes does not update the boardrooms_count when the City associated with the boardroom is changed. Is this a bug?

I was able to get around the update problem by implementing this before_save filter on the Boardroom model:

def update_boardrooms_counter
    if self.city_id_changed? && !self.new_record?
      City.update_counters self.city_id_was, :boardrooms_count => -1
      City.update_counters self.city_id, :boardrooms_count => 1
29 Nov 2012, 14:39
Sergio Lapenna (1 post)

This bug-issue with the update_attributes method has been resolved?

You must be logged in to comment