Counter cache for association counts

3938
0

Computing counts on associations can be expensive when done repeatedly—post.comments.count executes a SELECT COUNT(*) query every time. Counter caches solve this by maintaining a denormalized count column on the parent model that increments/decrements automatically when children are created or destroyed. This trades a small amount of write overhead (updating the counter) for massive read performance gains. I add counter_cache: true to the belongs_to association and create a migration to add the *_count column with a default of 0. For existing data, I use reset_counters to populate initial values. Counter caches work best for read-heavy associations where counts are displayed frequently, like comment counts or like counts on posts.