ruby
32 lines · 7 steps
How scopes compose in a Rails model
An Order model layers associations, enums, and reusable scopes that build on each other with subqueries.
Explained by
highlit
1class Order < ApplicationRecord
2 belongs_to :customer
3 has_many :line_items
4 has_many :products, through: :line_items
5
6 enum status: { pending: 0, paid: 1, shipped: 2, cancelled: 3 }
7
8 scope :recently_paid, -> {
9 where(status: :paid).where(paid_at: 30.days.ago..)
10 }
11
12 scope :for_active_customers, -> {
13 where(customer_id: Customer.active.select(:id))
14 }
15
16 scope :containing_discounted_products, -> {
17 discounted = Product.where("discount_percentage > 0").select(:id)
18 where(id: LineItem.where(product_id: discounted).select(:order_id))
19 }
20
21 scope :high_value_repeat_business, -> {
22 repeat_buyers = Order.paid
23 .group(:customer_id)
24 .having("COUNT(*) >= ?", 3)
25 .select(:customer_id)
26
27 for_active_customers
28 .where(customer_id: repeat_buyers)
29 .where("total_cents >= ?", 25_000)
30 .order(total_cents: :desc)
31 }
32end
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Named scopes return relations, so they chain and nest inside other scopes without triggering queries early.
- 2Passing a relation to where builds a SQL subquery, keeping filtering in the database instead of loading records into Ruby.
- 3Small, single-purpose scopes compose into complex business queries that stay readable and reusable.
Related explainers
rust
use serde::Deserialize; #[derive(Debug, Deserialize)] #[serde(untagged)]
Parsing flexible JSON shapes with serde
deserialization
enums
json
Intermediate
6 steps
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
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-scopes-compose-in-a-rails-model-explained-ruby-693c/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.