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

Ordering, Limits and Scopes

Scopes 12 minorder, limit and offset shape a result list, and scopes give reusable query pieces names so controllers read like sentences and can chain them.

ruby on rails / Ordering, Limits and Scopes

Explore each scene at your own pace.

01 · The rule

The rule

Ordering, Limits and Scopes

"The five newest available books" appears on the home page, in an email and in the API. Writing Book.where(available: true).order(created_at: :desc).limit(5) in three places is three chances to get it slightly different. Scopes give the pieces names, and ordering methods finish the query.

The rule

Name the filter as a scope, then chain: filter, order, limit.

Ordering and limiting:

Book.order(:title)                         # A to Z
Book.order(pages: :desc)                   # longest first
Book.order(author: :asc, title: :asc)      # by author, then title
Book.order(created_at: :desc).limit(5)     # five newest
Book.order(:id).limit(20).offset(40)       # the third page of 20
Book.order(:title).reverse_order           # flip an existing order

Scopes are named, reusable relations defined on the model:

class Book < ApplicationRecord
  scope :available, -> { where(available: true) }
  scope :long,      -> { where("pages > ?", 500) }
  scope :newest,    -> { order(created_at: :desc) }
  scope :by_author, ->(name) { where(author: name) }
end

Book.available.newest.limit(5)
Book.available.long.by_author("Tolkien")

A scope is a lambda (->) that returns a relation. It can take arguments. Scopes also work through associations: member.reviewed_books.available.

A scope and a class method (def self.available; where(available: true); end) are almost the same. The difference: if a scope's body returns nil or false, the scope returns all instead, so a chain never breaks.

default_scope applies a condition to every query on the model. It sounds convenient but surprises people later, because it also affects creates and associations. Prefer named scopes.

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