Skip to Main Content
Learning Rails
book

Learning Rails

by Simon St. Laurent, Edd Dumbill
November 2008
Beginner content levelBeginner
448 pages
12h 25m
English
O'Reilly Media, Inc.
Content preview from Learning Rails

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 find method is frequently called with a single id, as in find(id), but it can also be called with an array of ids, like find (id1, id2, id3, ...) in which case find will return an array of values. Finally, you can call find ([id1, id2]) and retrieve everything with id values between id1 and id2.

find all

Calling find with an argument of :all will return all the matching values as an array. (You can also abbreviate find(:all) to just .all—User.all, for example.)

find first

Calling find with an argument of :first will return the first matching value only. You’ll probably want to specify :order to be certain which value you get. (You can also abbreviate find(:first) to just .first—User.first, for example.)

find last

Calling find with an argument of :last will return the last matching value only. As with find(:first), you’ll probably want to specify :order to be certain which value you get. (Again, you can abbreviate find(:last) to just .last—User.last, for example.)

The options give you much more control over what is queried ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Learning Rails 5

Learning Rails 5

J. Mark Locklear, Eric J Gruber, Barnabas Bulpett
Mastering Ruby Closures

Mastering Ruby Closures

Benjamin Tan Wei Hao
Ruby on Rails® Bible

Ruby on Rails® Bible

Timothy Fisher

Publisher Resources

ISBN: 9780596154943Supplemental ContentErrata