Forum: Ruby on Rails Better counter_caches

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.
Joe (Guest)
on 2006-02-28 00:25
Hey everybody,

Rails currently offers 'belongs_to :counter_cache', which is a very
basic replacement for count triggers:

":counter_cache - caches the number of belonging objects on the
associate class through use of increment_counter and decrement_counter.
The counter cache is incremented when an object of this class is created
and decremented when itâ??s destroyed. This requires that a column named
"#{table_name}_count" (such as comments_count for a belonging Comment
class) is used on the associate class (such as a Post class)."

So, all that's possible is incrementing/decrementing
"#{table_name}_count" when an item is created or destroyed. I think it'd
be useful if :counter_cache also had this functionality:

- ability to specify the count columns (I also maintain counts of active
members, items, etc.; so..."active_members_count, active_items_count,

- ability to specify a function (probably belonging to the parent model)
which could inspect the child object, which of its properties (like via
PostgreSQL's OLD/NEW vars) changed, then update count columns

Any other thoughts?

This topic is locked and can not be replied to.