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
class ToastBroadcaster include ActionView::RecordIdentifier def self.broadcast_to(user, message:, type: :notice)
How Turbo Stream toasts broadcast in Rails
turbo-streams
service-object
real-time
Intermediate
6 steps
ruby
class TemplateInterpolator PLACEHOLDER = /\{\{\s*([\w.]+)\s*\}\}/ def initialize(strict: false)
Interpolating templates with dotted keys in Ruby
regex
string-interpolation
hash-traversal
Intermediate
6 steps
ruby
class KeyTransformer def self.camelize(data) new.camelize(data) end
Recursively camelizing nested Ruby data
recursion
data-transformation
pattern-matching
Intermediate
7 steps
ruby
module Paginatable extend ActiveSupport::Concern private
A reusable pagination concern in Rails
pagination
concerns
http-headers
Intermediate
8 steps
ruby
class Api::MessagesController < ApiController before_action :authenticate_api_key! rate_limit to: 100,
Layered API rate limiting in Rails
rate-limiting
api-authentication
throttling
Intermediate
9 steps
ruby
class Order < ApplicationRecord include AASM belongs_to :warehouse
Modeling an order lifecycle with AASM in Rails
state machine
guards
callbacks
Intermediate
10 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.