ActiveRecord querying: where/find_by
This course covers filtering records in ActiveRecord with .where and find_by. It starts with a multi-key hash, where every condition is joined with AND. Ranges generate BETWEEN and arrays generate IN. .where.not negates a condition, and .or joins two relations with OR. Chained .where calls produce the same SQL as one hash, and the relation stays lazy. find_by accepts several attributes and returns one match or nil, while find_by! raises ActiveRecord::RecordNotFound. A closing challenge rebuilds the AND matching in plain Ruby.
What you'll learn
- ✓Combining several conditions in one .where hash with AND
- ✓Using ranges and arrays to generate BETWEEN and IN
- ✓Negating conditions with .where.not and joining relations with .or
- ✓Chaining .where calls to build a lazy query across several lines
- ✓Looking up one record with find_by and several attributes
- ✓Raising ActiveRecord::RecordNotFound with find_by! when nothing matches
.where with several conditions at once
The lesson "find_by: the same idea, without the crash" in ActiveRecord: finding records showed the basic shape. Article.find_by(title: "Nonexistent") looks up one attribute and returns nil when nothing matches. That lesson left the rest for a later course: find_by with several conditions, chaining…
Read the full lesson free →Curriculum
7 lessons.where with several conditions at once
A .where hash with several keys joins every condition with AND, as .to_sql shows in the generated query.
Ranges and arrays: BETWEEN and IN, in Ruby
A Range value generates BETWEEN and an Array value generates IN, both still joined with AND to other keys.
.where.not and .or: negation and alternatives
The .where.not method negates a condition, including NULL behavior, and .or joins two relations on one table with OR.
Chaining multiple .where calls
Chained .where calls produce the same AND query as one hash, and the lazy relation suits conditional filtering code.
find_by with several attributes at once
With several attributes, find_by builds an AND condition with LIMIT 1, like .take, and returns one row or nil.
find_by!: the loud version
The find_by! method raises ActiveRecord::RecordNotFound on a miss, and a sandbox console is a safe place to try queries.
Putting it together: filtering records
A review of each lesson in eight lines of code, plus a plain Ruby challenge over an array of hashes.