find vs find_by vs where
dynamic-finders, rails-activerecord, ruby-on-rails
Solution
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).
Problem
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?