ruby
31 lines · 8 steps
Aggregating post stats in a Rails scope
A single scope computes per-author aggregates in SQL, with reader methods that gracefully fall back when the columns aren't loaded.
Explained by
highlit
1class Author < ApplicationRecord
2 has_many :posts
3
4 scope :with_post_stats, -> {
5 left_joins(:posts)
6 .select(
7 "authors.*",
8 "COUNT(posts.id) AS posts_count",
9 "COALESCE(SUM(posts.views), 0) AS total_views",
10 "MAX(posts.published_at) AS last_published_at"
11 )
12 .group("authors.id")
13 }
14
15 def posts_count
16 read_attribute(:posts_count) || posts.count
17 end
18
19 def total_views
20 read_attribute(:total_views).to_i
21 end
22
23 def last_published_at
24 value = read_attribute(:last_published_at)
25 value.is_a?(String) ? Time.zone.parse(value) : value
26 end
27
28 def active_publisher?
29 last_published_at.present? && last_published_at > 90.days.ago
30 end
31end
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Pushing COUNT/SUM/MAX into a single grouped query avoids N+1 queries across authors.
- 2Aliased SQL columns surface as read-only attributes you access with read_attribute.
- 3Guarding computed readers keeps models correct whether or not the aggregate scope was applied.
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/aggregating-post-stats-in-a-rails-scope-explained-ruby-3692/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.