I am new to rails. What I see that there are a lot of ways to find a record:
find_by_<columnname>(<columnvalue>)
find(:first, :conditions => { <columnname> => <columnvalue> }
where(<columnname> => <columnvalue>).first
And it looks like all of them end up generating exactly the same SQL. Also, I believe the same is true for finding multiple records:
find_all_by_<columnname>(<columnvalue>)
find(:all, :conditions => { <columnname> => <columnvalue> }
where(<columnname> => <columnvalue>)
Is there a rule of thumb or recommendation on which one to use?
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.
find_by accepts a key value pair as a parameter by which to search the data structure. If the object is found, it is returned. If it is not, a nil value is returned and your program continues to function without exception.
find_by returns an object, yet where returns a collection.
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.
where returns ActiveRecord::Relation
Now take a look at find_by implementation:
def find_by
where(*args).take
end
As you can see find_by is the same as where but it returns only one record. This method should be used for getting 1 record and where should be used for getting all records with some conditions.
Edit: This answer is very old and other, better answers have come up since this post was made. I'd advise looking at the one posted below by @Hossam Khamis for more details.
Use whichever one you feel suits your needs best.
The find
method is usually used to retrieve a row by ID:
Model.find(1)
It's worth noting that find
will throw an exception if the item is not found by the attribute that you supply. Use where
(as described below, which will return an empty array if the attribute is not found) to avoid an exception being thrown.
Other uses of find
are usually replaced with things like this:
Model.all
Model.first
find_by
is used as a helper when you're searching for information within a column, and it maps to such with naming conventions. For instance, if you have a column named name
in your database, you'd use the following syntax:
Model.find_by(name: "Bob")
.where
is more of a catch all that lets you use a bit more complex logic for when the conventional helpers won't do, and it returns an array of items that match your conditions (or an empty array otherwise).
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