ruby
34 lines · 6 steps
How counter caches work in Rails
A counter_cache column keeps a running tally of associated records so you never pay for a COUNT query.
Explained by
highlit
1class CreateCommentsWithCounterCache < ActiveRecord::Migration[7.1]
2 def change
3 create_table :posts do |t|
4 t.string :title, null: false
5 t.integer :comments_count, null: false, default: 0
6 t.timestamps
7 end
8
9 create_table :comments do |t|
10 t.references :post, null: false, foreign_key: true
11 t.text :body, null: false
12 t.timestamps
13 end
14 end
15end
16
17class Post < ApplicationRecord
18 has_many :comments, dependent: :destroy
19end
20
21class Comment < ApplicationRecord
22 belongs_to :post, counter_cache: true
23end
24
25class BackfillPostCommentsCount < ActiveRecord::Migration[7.1]
26 def up
27 Post.find_each do |post|
28 Post.reset_counters(post.id, :comments)
29 end
30 end
31
32 def down
33 end
34end
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1A counter_cache trades a little write-time bookkeeping for fast, query-free association counts.
- 2The cache column must be non-null with a default of 0 so increments and decrements stay consistent.
- 3reset_counters recomputes tallies from scratch, which is essential when backfilling an existing table.
Related explainers
ruby
require "shellwords" require "open3" module Backup
Building safe shell commands in Ruby
shell-out
subprocess
command-injection
Intermediate
7 steps
ruby
class UserAgentParser BROWSERS = [ [/Edg\/([\d.]+)/, "Edge"], [/OPR\/([\d.]+)/, "Opera"],
Parsing user-agent strings in Ruby
regex
pattern-matching
lookup-tables
Intermediate
8 steps
ruby
class LogAggregator BUCKET_FORMAT = "%Y-%m-%dT%H:%M" def initialize(entries)
Bucketing log entries by the minute in Ruby
aggregation
hashing
enumerable
Intermediate
5 steps
ruby
class WeeklySignupsReport DEFAULT_WEEKS = 12 def initialize(weeks: DEFAULT_WEEKS, source: User.all)
Building a weekly signups report in Rails
service object
aggregation
group by
Intermediate
7 steps
ruby
class ApplicationController < ActionController::Base EXPERIMENTS = { checkout_button_color: %w[control blue green], onboarding_flow: %w[control streamlined]
How A/B test cohorts are assigned in Rails
a-b-testing
cookies
hashing
Intermediate
8 steps
ruby
class SnippetHighlighter CONTEXT_RADIUS = 60 MAX_TERMS = 8
Building search-result snippets in Ruby
regular-expressions
text-processing
search
Intermediate
9 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/how-counter-caches-work-in-rails-explained-ruby-f696/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.