Finders
ORM::ActiveRecord provides a range of class-level finder methods for locating records.
find
find($id) looks up a record by primary key. It raises X::RecordNotFound
if no row matches.
1 2 3 4 5 6 7 8 9 10 11 12 13 | |
find-by
find-by(%conditions) returns the first matching record, or Nil if there is
no match.
1 2 3 4 | |
find-by-or-die(%conditions) raises X::RecordNotFound instead of returning
Nil.
1 | |
first / last / take
first and last return a single record ordered by id. take returns up
to N records with no order guarantee.
1 2 3 4 5 | |
When you need a different order, chain .order before .first / .last:
1 | |
first(N) / last(N)
Pass an integer to get back an array of up to N records.
1 2 3 4 5 6 | |
first(0) and last(0) return an empty list.
sole / find-sole-by
sole returns the single record matched by a relation. Raises
X::RecordNotFound if there are zero matches, or X::SoleRecordExceeded
if there are two or more.
1 2 3 | |
find-sole-by(%conditions) is the class-level shorthand:
1 | |
find-or-create-by / find-or-initialize-by
find-or-create-by(%attrs) returns the first row matching %attrs, or
creates one with those attributes if no row matches. The returned record may
be invalid if creation failed validation — is-invalid is True and
errors is populated.
1 2 3 4 | |
find-or-create-by-or-die(%attrs) raises X::RecordInvalid instead of
returning an invalid record.
find-or-initialize-by(%attrs) is the no-save variant: returns the existing
record if found, or builds an unsaved record otherwise.
1 2 3 | |
When called on a relation, prior where conditions are merged into the
create attributes:
1 2 3 | |
create-with
create-with(%attrs) attaches default attributes to a relation. They flow
into a record created via find-or-create-by / find-or-initialize-by, but
are not used as where conditions for the find step.
1 2 | |
Find-step parameters always win over create-with defaults if a key
overlaps.
pick
pick(*@cols) returns a single row's values without instantiating a model.
For one column, it returns the scalar value. For multiple columns, it
returns an array. Returns Any when no row matches.
1 2 3 4 | |
exists
exists returns True if any row matches.
1 2 | |