I've noticed that the Model.where
method always returns an array even if there is only one result where as the Model.find
method doesn't. Is there any reason for this? I thought Model.where
was the preferred function since Rails 3.X.
Should I be using Model.find
when I expect a single result and Model.where
when I expect more than one result?
The additional difference between find() and find_by() is that find could only be used to search by primary key (usually the 'id') while the find_by() requires and searches by attribute (either passed as hash like Employee. find_by(name: 'Mike') or using the Employee.
Mind that find_by doesn't throw any exception by default. If the result is an empty set, it returns nil instead of find . If the exception is needed may use find_by! that raises an ActiveRecord::RecordNotFound error like find .
where returns an ActiveRecord::Relation (not an array, even though it behaves much like one), which is a collection of model objects. If nothing matches the conditions, it simply returns an empty relation. find (and its related dynamic find_by_columnname methods) returns a single model object.
find_by is very similar to Model. find and lets you search any column or group of columns in your database but it returns nil if no record matches the search.
where
returns an ActiveRecord::Relation
(not an array, even though it behaves much like one), which is a collection of model objects. If nothing matches the conditions, it simply returns an empty relation.
find
(and its related dynamic find_by_columnname
methods) returns a single model object. If nothing is found, an ActiveRecord::RecordNotFound
exception is raised (but not with the dynamic find_by_
methods).
While find
can return an Array of records—not a Relation—if given a list of IDs, using where
is preferred since Rails 3. Many similar uses of find
are now deprecated or gone entirely.
So yes, if you only want and expect a single object, using find
is easier, as otherwise you must call Model.where.first
.
Note that old-style hash options to find
and many dynamic find_
methods are deprecated as of Rails 4.0 (see relevant release notes).
Actually find_by
takes a model object from where
obtained ActiveRecord::Relation
def find_by(*args) where(*args).take end
Source
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With