views:

109

answers:

1

I rely on a counter cache value in an after_create hook of my model. However, my hook is called before the counter cache gets updated, thus breaking a computation.

Is there any way to force a counter cache "flush" so that I always see an up-to-date value in after_create?

+1  A: 

Make sure your after_create :callback statement is after the has_many/belongs_to definition.

If it doesn't work, you can create your own counter cache (it's nothing more than a call to increment/decrement, see add_counter_cache_callbacks) and ensure it's called before your code.

Simone Carletti
thanks, I'll have a look at that.
Matthias
by the way, I could work around it by moving the callback to after_save, and returning unless self.id_changed? (making it equivalent to an after_create hook, just that's it's called later down the chain).
Matthias
that fixed it, thanks a lot
Matthias