If you want to have a supported counter at all, using counter_cache or doing it manually, Rails will support your counters with callbacks, which will increase / decrease the counter when a new child is created / destroyed.
I am not aware of counter_cache storage counter_cache without using the belongs_to relationship, because only the parent can store the number of children.
Weight Performance
If your table is βlargeβ, populate the test database with a large number of rows, and then run some SQL queries using EXPLAIN to get database query performance. See if the performance achieved by creating / destroying a record using counter_cache is offset by how often you have to access these counters in the first place.
If the counter should not be 100% accurate, you can periodically update caches using cron job or background worker.
In short:
- You only need to use counter_cache if you need these counters to compensate for a bit more time spent on creating / deleting the record.
- Using
counter_cache compared to the manual alternative using callbacks, as far as I know, is unlikely to result in a significant performance loss. - If the cache does not need to be accurate, take advantage of this and perform calculations less frequently.
source share