# Ruby on Rails: Improve App Performance with Counter Caches
Counter caches can significantly improve your Ruby on Rails application’s performance by helping you avoid expensive database queries when counting associated records.
Consider a scenario where you have a Post model and a Comment model, and you
want to display the number of comments for each post. Without counter caches,
you might use the following code to count the comments for a post, which
triggers a database query every time you need to count the comments, impacting
your app’s performance:
post.comments.count
To implement a counter cache, first, add a new column to the parent model
(posts in this example) with a _count suffix. This command creates a
migration to add the comments_count column to the posts table:
# rails generate migration AddCommentsCountToPosts comments_count:integer
# db/migrate/YYYYMMDD_add_comments_count_to_posts.rb
class AddCommentsCountToPosts < ActiveRecord::Migration[6.1]
def change
add_column :posts, :comments_count, :integer, default: 0, null: false
end
end
Run the migration to apply the changes to the database:
rails db:migrate
Now, update the belongs_to association in the child model to include the
counter_cache option, which will automatically update the comments_count
column in the posts table whenever a comment is added or removed. Finally,
update the existing records in the database to reflect the correct count. You
can execute this code in the Rails console or create a one-time rake task.
# app/models/comment.rb
class Comment < ApplicationRecord
belongs_to :post, counter_cache: true
end
# ...
Post.find_each { |post| Post.reset_counters(post.id, :comments) }
With the counter cache in place, you can now use the counter cache column to display the number of comments for a post, eliminating the need for additional database queries and improving your app’s performance:
post.comments_count
By using counter caches in your Ruby on Rails application, you can optimize performance and enhance user experience by avoiding expensive database queries when counting associated records.