Find, First, Last, Offset, Limit
You may want to fetch one model instead of a collection.
Find
Collection#find
allows to fetch a model based on an expression.
There's two flavors for find
method: find
and find!
. The first one return a nilable type, which will be nil
if not found, while the second return a model or throw an exception if not found.
Example
First / Last
First and last return the first and last row of a SELECT query.
In the case of first, it will order by [primary key column] ASC
if no order_by
directive is found. In the case of last, it will invert the direction of the order directive, turning each ASC
to DESC
and vice-versa before performing the call.
Both return a model instead of an enumeration of models.
Like with find
, first!
/first
and last
/last!
are existing variant of the method
Offset and Limit
Offset and limit provide a way to scope a request or do some pagination.
Offset
The code above will fetch the model from position 5 .. 10
of the query.
It is possible to write the same behavior as above by using []
operator:
Nothing to be aware: []
operator will resolve the query, calling it and return an Array of model, not a Collection object anymore.
You may use the []
operator with a number as parameter instead of range. In this case, it's equivalent to offset(number).first!
. The []?
operator is equivalent to offset(number).first
and will return nilable
reference.
Last updated