counter_cache not updating on the model after save

Posted by sehnsucht on Stack Overflow See other posts from Stack Overflow or by sehnsucht
Published on 2012-11-24T23:00:53Z Indexed on 2012/11/24 23:03 UTC
Read the original article Hit count: 124

I am using a counter_cache to let MySQL do some of the bookkeeping for me:

class Container
  has_many :items
end

class Item
  belongs_to :container, :counter_cache => true
end

Now, if I do this:

container = Container.find(57)
item = Item.new
item.container = container
item.save

in the SQL log there will be an INSERT followed by something like:

UPDATE `containers` SET `items_count` = COALESCE(`items_count`, 0) + 1
    WHERE `containers`.`id` = 57

which is what I expected it to do. However, the container[:items_count] will be stale!

...unless I container.reload to pick up the updated value. Which in my mind sort of defeats part of the purpose of using the :counter_cache in favor of a custom built one, especially since I may not actually want a reload before I try to access the items_count attribute. (My models are pretty code-heavy because of the nature of the domain logic, so I sometimes have to save and create multiple things in one controller call.)

I understand I can tinker with callbacks myself but this seems to me a fairly basic expectation of the simple feature. Again, if I have to write additional code to make it fully work, it might as well be easier to implement a custom counter.

What am I doing/assuming wrong?

© Stack Overflow or respective owner

Related posts about ruby-on-rails

Related posts about counter-cache