Better counter_caches


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?