Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails .where vs .find

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?

like image 386
AdamB Avatar asked Mar 05 '12 21:03

AdamB


People also ask

What is the difference between find and Find_by in rails?

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.

What does Find_by return in rails?

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 .

What does where return in rails?

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.

What is Find_by?

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.


2 Answers

  • 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).

like image 100
Andrew Marshall Avatar answered Oct 06 '22 03:10

Andrew Marshall


Actually find_by takes a model object from where obtained ActiveRecord::Relation

def find_by(*args)   where(*args).take end 

Source

like image 39
Kamil Lelonek Avatar answered Oct 06 '22 02:10

Kamil Lelonek