ruby 34 lines · 7 steps

A custom counter cache in Rails

Maintaining an approved-comment count on Post without relying on Rails' built-in counter cache.

Explained by highlit
1class Post < ApplicationRecord
2 belongs_to :author, counter_cache: false
3 has_many :comments, dependent: :destroy
4end
5 
6class Comment < ApplicationRecord
7 belongs_to :post
8 
9 after_commit :refresh_post_comment_count, on: [:create, :destroy]
10 
11 private
12 
13 def refresh_post_comment_count
14 post.refresh_comments_count!
15 end
16end
17 
18class Post < ApplicationRecord
19 def refresh_comments_count!
20 fresh_count = comments.where(approved: true).count
21 
22 return if fresh_count == comments_count
23 
24 update_columns(
25 comments_count: fresh_count,
26 comments_count_refreshed_at: Time.current
27 )
28 end
29 
30 def stale_comments_count?
31 comments_count_refreshed_at.nil? ||
32 comments_count_refreshed_at < 1.hour.ago
33 end
34end
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1A custom counter lets you count a filtered subset that Rails' built-in `counter_cache` can't express.
  2. 2Firing off `after_commit` ensures the count updates only once the transaction has actually persisted.
  3. 3Skipping unchanged writes and using `update_columns` keeps the refresh cheap and callback-free.

Related explainers

Share this explainer

Here's the card — post it anywhere.

A custom counter cache in Rails — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code