Skip to the workspace
Pebellslearn by building
Active Record Queries  ›  Lesson

Basic Queries and Conditions

Conditions 15 minfind, find_by and where fetch records; where returns a lazy relation you can keep chaining, and conditions should use hashes or ? placeholders rather than string interpolation.

ruby on rails / Basic Queries and Conditions

Explore each scene at your own pace.

01 · The rule

The rule

Basic Queries and Conditions

A controller needs "book 7", "the member with this email", "all available books over 300 pages". Each is a database query, and Active Record lets you write each one as a short Ruby expression. The skill is knowing which method to reach for and what it gives back when nothing matches.

The rule

find by id, find_by for one, where for many — and never interpolate.

Book.find(7)                         # one Book, or raises RecordNotFound
Book.find_by(title: "Dune")          # first match, or nil
Book.where(available: true)          # a relation: zero or more books
Method Returns When nothing matches
find(id) one record raises ActiveRecord::RecordNotFound (a 404 page)
find_by(...) one record nil
where(...) a relation (list) an empty relation

Conditions come in three styles:

Book.where(author: "Le Guin")                  # hash: equality
Book.where(author: ["Le Guin", "Pratchett"])   # hash with array: IN (...)
Book.where(pages: 300..500)                    # hash with range: BETWEEN
Book.where(pages: 301..)                       # endless range: pages >= 301
Book.where("pages > ?", 300)                   # string with a ? placeholder
Book.where.not(available: true)                # NOT
Book.where(available: false).or(Book.where(pages: ..100))

where does not hit the database straight away. It builds a relation, a query-in-progress, and you can keep chaining: Book.where(available: true).where("pages > ?", 300) becomes one SQL query with AND. The query runs only when you need the rows — when you loop, call to_a, first, count or pluck(:title).

Handy extras: Book.first, Book.last, Book.take, Book.exists?(title: "Dune"), Book.pluck(:title) (an array of titles, no model objects).

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.