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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1A custom counter lets you count a filtered subset that Rails' built-in `counter_cache` can't express.
- 2Firing off `after_commit` ensures the count updates only once the transaction has actually persisted.
- 3Skipping unchanged writes and using `update_columns` keeps the refresh cheap and callback-free.
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/a-custom-counter-cache-in-rails-explained-ruby-e897/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.