Relations
User.where(...), User.order(...), and friends return a chainable relation
that defers running SQL until you ask for results. Relations compose: every
scope-narrowing call returns a new relation, leaving the original untouched.
1 2 3 4 5 | |
Realising a relation
Relations stay lazy until you call one of these methods:
| Method | Returns |
|---|---|
.all |
List of model instances |
.first |
One instance ordered by id ASC, or Nil |
.last |
One instance ordered by id DESC, or Nil |
.count |
Int — COUNT(*) |
.exists |
Bool |
.pluck(...) |
List of raw column values |
.ids |
List of id column values (= pluck('id')) |
where
where(%conditions) adds equality conditions joined with AND. Conditions
are bound as parameters, never interpolated, so user-supplied values are safe.
1 | |
You can chain further .where(...) calls to merge in additional conditions.
1 2 3 | |
where accepts several value shorthands beyond a literal scalar:
1 2 3 4 | |
See Queries for the full filtering vocabulary, including
where.not, where.missing, where.associated, or, and, merge,
rewhere, unscope, and excluding.
order
order(*@cols) adds ORDER BY clauses. Pass column names or fully formed
fragments like 'fname DESC'.
1 2 3 | |
reorder(...) replaces any prior order clauses. in-order-of(:col, [...])
orders rows to match an explicit value list.
1 2 | |
limit and offset
limit(N) and offset(N) add LIMIT and OFFSET. Useful for pagination.
1 2 3 | |
SQLite and MySQL require a LIMIT whenever an OFFSET is set; the adapter
adds a synthetic unbounded LIMIT when you pass offset alone.
all
Model.all returns a relation that, once realised, returns every row. You can
chain conditions onto it just like where.
1 | |
none
Model.none returns a chainable null relation. Every operation that would
hit the database returns the empty result for its return type ([], 0,
False, Nil, …) without issuing SQL. Useful as a "no match" return value
from helper methods that must still hand back a chainable relation.
1 2 3 4 5 6 7 | |
none is sticky once set; further where, order, etc. compose but the
result stays empty. merge(other.none) propagates the null relation.
pluck and ids
pluck returns raw column values without instantiating model objects. It is
much cheaper than materialising records and dropping everything but one
column.
1 2 3 4 5 | |
ids is the common shorthand for pluck('id').
1 | |
count and exists
count returns the number of matching rows. exists returns True if any
row matches.
1 2 | |