DEV Community

Cover image for TLDR: counter_cache - field to count how many children a records has
Yaroslav Shmarov
Yaroslav Shmarov

Posted on • Originally published at blog.corsego.com

2

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

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs