TLDR: counter_cache - field to count how many children a records has

superails

Yaroslav Shmarov

Posted on February 17, 2021

TLDR: counter_cache - field to count how many children a records has

Often you want to count how many child records a record has (user.posts.count, user.comments.count).
Storing this data in a the database is more efficient (like user.posts_count, user.comments_count) than recalculating it each time.
counter_cache gives us a way to recalculate the database field containing count of child records whenever a child record is created/deleted

HOWTO

user.rb

has_many :posts
Enter fullscreen mode Exit fullscreen mode

post.rb - add counter_cache: true to recalculate posts_count field in user table

belongs_to :user, counter_cache: true
Enter fullscreen mode Exit fullscreen mode

console:

rails g migration add_posts_count_to_users posts_count:integer
Enter fullscreen mode Exit fullscreen mode

migration:

add_column :users, :posts_count, :integer, default: 0, null: false
Enter fullscreen mode Exit fullscreen mode

rails c - recalculate posts_count for all existing posts and users

User.find_each { |u| User.reset_counters(u.id, :posts) }
Enter fullscreen mode Exit fullscreen mode
💖 💪 🙅 🚩
superails
Yaroslav Shmarov

Posted on February 17, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related