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
ruby
module RequestTagging class Middleware def initialize(app) @app = app
Per-request context with CurrentAttributes in Rails
middleware
thread-safety
logging
Intermediate
7 steps
ruby
class Spellchecker ALPHABET = ('a'..'z').to_a.freeze def initialize(dictionary)
Building a Norvig-style spellchecker in Ruby
edit-distance
levenshtein
dynamic-programming
Advanced
10 steps
ruby
require "charlock_holmes" class TextFileNormalizer DEFAULT_CONFIDENCE = 60
Normalizing text files to clean UTF-8 in Ruby
encoding
text-processing
file-io
Intermediate
8 steps
ruby
require 'date' require 'set' class BusinessDayCalculator
Counting business days in Ruby
dates
sets
ranges
Intermediate
8 steps
ruby
class Document < ApplicationRecord class StaleObjectError < StandardError def initialize(id) super("Document ##{id} was modified by another process")
Optimistic locking with retries in Rails
optimistic-locking
concurrency
transactions
Advanced
8 steps
ruby
class BackfillUsersFullName < ActiveRecord::Migration[7.1] disable_ddl_transaction! BATCH_SIZE = 5_000
How to backfill a column safely in Rails
migrations
batching
backfill
Intermediate
7 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.