What is counter_cache in Rails?

Answer

counter_cache is an optimization that stores the count of associated records in a cached column on the parent model, avoiding a COUNT(*) SQL query every time you need the count. Add counter_cache: true to the belongs_to declaration: belongs_to :post, counter_cache: true. Rails maintains a comments_count column on the posts table automatically, incrementing/decrementing it when records are created/destroyed. Access with post.comments.size (uses cache) vs post.comments.count (always hits DB). Add the column via migration: add_column :posts, :comments_count, :integer, default: 0.