If you want to have a maintained counter at all, whether using counter_cache
or doing it manually, Rails will maintain your counters using callbacks, which will increase/decrease the counter when a new descendant is created/destroyed.
I am not aware of a means to store a counter_cache
without using the belongs_to
relationship, because only the parent can store the count of the children.
Weighing Performance
If your table is going to get 'large', populate your test database with a large number of rows then start running some SQL queries using EXPLAIN
to get the performance of your database queries. See if the performance hit in doing record creation/destruction with counter_cache
is offset by how often you need to access these counters in the first place.
If the counter does not need to be 100% accurate at all times, you can instead update the caches periodically using a cron
job or background worker.
In summary:
- You should only use counter_cache if you need those counters enough to offset the slightly longer time taken to create/destroy a record.
- Using
counter_cache
vs a manual alternative that uses callbacks is, as far as I am aware, unlikely to result in much of a detriment to performance.
- If the cache does not need to be accurate, take advantage of that and perform the calculations less often.