Finding Data with ActiveRecord
The find method is common
in Rails, usually in controllers. It’s constantly used as find(id) to
retrieve a single record with a given id, and also used as find(:all) to retrieve an entire set of
records. The find method is, however,
capable of much more finesse, letting you control which records are
returned and in what order. There are four basic ways to call find, and then a set of options that can apply
to all of those uses:
- find by
id The
findmethod is frequently called with a singleid, as infind(id), but it can also be called with an array ofids, likefind(id1, id2, id3, ...) in which casefindwill return an array of values. Finally, you can callfind([id1, id2])and retrieve everything withidvalues betweenid1andid2.- find all
Calling
findwith an argument of:allwill return all the matching values as an array. (You can also abbreviatefind(:all)to just.all—User.all, for example.)- find first
Calling
findwith an argument of:firstwill return the first matching value only. You’ll probably want to specify:orderto be certain which value you get. (You can also abbreviatefind(:first)to just.first—User.first, for example.)- find last
Calling
findwith an argument of:lastwill return the last matching value only. As withfind(:first), you’ll probably want to specify:orderto be certain which value you get. (Again, you can abbreviatefind(:last)to just.last—User.last, for example.)
The options give you much more control over what is queried ...