Understanding Rails · Season 3: Active Record in depth
Querying
Episode 19 · deep dive · about 5 minutes · Rails 8.1 · by Tommy A. Caruso
How was this episode?
The series' author reads every note, and no one else sees it. When something is wrong or unclear, it gets fixed and the episode re-cut. How this series stays right.
Not endorsed yet. Are you a Rails developer? What's an endorsement?
Endorse this version To endorse: create an account, confirm your email, then link GitHub.
What changed
- Version 2, November 20, 2026: A missing record becomes a 404 page in production, not everywhere.
where, order, joins, includes, and the queries each one writes.
Free to watch. If it helped, support the series.
Transcript
0:00 Querying
Episode nineteen. Querying. Active Record turns Ruby into SQL. Today we'll write the queries you'll use every week, and read the SQL behind every one, because the SQL is what actually runs.
0:17 A relation waits
Start with a surprise. Note dot order, created at descending, dot limit two, runs nothing. It returns a relation: a query, waiting. You can keep adding to it, and ask for its SQL with to SQL. Only when you need the records, here with pluck, does the database hear from you.
0:35 where with a hash
Where takes a hash. Note dot where, notebook, work. Rails turns the notebook into its id, and writes where notebook id equals six. You talk in models. Rails talks in columns.
0:48 Arrays and ranges
Give where an array, and you get in: body in, ship it, call mom. Give it a range, and you get a comparison. Created at, from November eleventh onward, becomes greater than or equal to. No SQL strings needed.
1:02 not and or
Where dot not flips a condition: notebook id is not six. And or joins two queries: body is ship it, or body is call mom, in one statement, with the parentheses in the right place.
1:15 Placeholders
Sometimes you need SQL Rails can't build from a hash, like a LIKE. Write the SQL as a string, with a question mark where the value goes, and pass the value after it. Rails quotes the value for you.
1:29 SQL injection
Here's why that matters. Put a value straight into the string instead, and someone types, x, quote, or one equals one. The SQL becomes where body equals x, or one equals one, which is always true. Every note comes back: five of them. Pass the same text as a hash value, and Rails quotes it, and zero notes match. Never put a request's value inside a SQL string.
1:53 order, limit, first
Order sorts, and limit cuts. First adds limit one, and if you didn't order, it orders by id, so first means the oldest row you inserted, not the one you see first on screen. Say the order you mean.
2:07 find and find_by
Find takes an id, and when nothing matches, it raises record not found. In production, Rails turns that into a four oh four page. Find by takes any columns, and returns nil instead. Use find when a missing record is an error, and find by when it's a question.
2:25 pluck
When you need values, not models, use pluck. Pluck body selects only the body column, and gives you plain strings. No objects are built, so it's faster, and it uses less memory.
2:38 count, exists?, size
Three ways to ask how many. Count always asks the database: select count. Exists asks the cheapest question there is: select one, limit one. And size is smart: before the records load, it counts with SQL, and after they load, it counts what's already in memory.
2:56 joins
Joins follows an association into SQL. Note dot joins tags, where the tag name is urgent. Rails writes both inner joins, through taggings to tags, and returns the notes tagged urgent: ship it, and call mom.
3:11 left_joins
Joins keeps only rows that match. To find what has no match, use left joins. Notebooks, left joined to notes, where the note id is null: the notebooks with no notes at all. Here, that's Ideas.
3:25 group
Group answers how many of each. Note dot group, notebook id, dot count, returns a hash: notebook six has three notes, notebook seven has two. Join to notebooks and group by name, and the keys become readable: Home, two. Work, three.
3:42 includes
Includes loads an association ahead of time. Note dot includes notebook runs two queries: all the notes, then all their notebooks, in one go, with where id in six and seven. That one change is the cure for the next episode's problem.
3:58 Eager loading
Add a where on the included association, and Rails switches strategy. It writes one big query, joining tags, and loads notes and tags together from it. That's eager load. Rails picks the strategy for you; to SQL shows you which.
4:14 Scopes
Queries you repeat deserve a name. In the model, scope recent orders by created at descending. Scope about takes a word, and finds notes that mention it. Now work dot notes, about milk, recent, limit one, reads like a sentence, and it's still one query.
4:31 find_each
Last, the loop that won't sink your server. Note dot all dot each loads every row at once. Find each loads them in batches, a thousand by default, each batch starting after the last id it saw. Use it whenever a table could be big.
4:47 The rules
So: let the database do the work, with where, joins, and group, instead of filtering in Ruby. Never put a request's value inside a SQL string. Pluck when you need values. And when you're unsure, ask for to SQL, and read it.
Next: the N plus one query, the slow page you'll write by accident, and how to spot it and fix it.
Check your understanding
-
A search box sends text that will be matched with LIKE. Which query is safe?
- Note.where("body LIKE '%#{params[:q]}%'")
- Note.where("body LIKE ?", "%#{params[:q]}%")
- Note.where("body LIKE " + params[:q])
Show answer
Note.where("body LIKE ?", "%#{params[:q]}%"). With a question mark, Rails quotes the value for you. Putting the value inside the SQL string lets someone type SQL of their own. Source: Active Record Query Interface: array conditions (Rails Guides 8.1).
-
No note has id 999. What does Note.find(999) do, and what does Note.find_by(id: 999) do?
- Both return nil
- Both raise ActiveRecord::RecordNotFound
- find returns nil, and find_by raises
- find raises ActiveRecord::RecordNotFound, and find_by returns nil
Show answer
find raises ActiveRecord::RecordNotFound, and find_by returns nil. Use find when a missing record is an error, and find_by when it is a question you expect to answer with nil. Source: Active Record Query Interface: retrieving a single object (Rails Guides 8.1).
-
You call Note.first with no order. Which note comes back?
- The one with the lowest id
- The one created most recently
- Whichever row the database reads first
Show answer
The one with the lowest id. first orders by the primary key when you give no order, so it is the oldest row inserted. Say the order you mean. Source: Active Record Query Interface: first (Rails Guides 8.1).
-
notes = Note.where(notebook: work). You call notes.size before the notes are loaded, and again after notes.to_a. What runs?
- A COUNT query both times
- A COUNT query the first time, and no query the second time
- No query either time
- It loads every note both times
Show answer
A COUNT query the first time, and no query the second time. size counts with SQL until the records are loaded, then counts the records already in memory. Source: ActiveRecord::Relation (Rails source, v8.1.4.1).
Sources
Every example in this episode was run on Rails 8.1.4.1 and Ruby 4.0.2.