Rails 2.1: The First and the Last

It’s no news that ActiveRecord allows you to easily get the first record of any type of model, like so:


first = Donation.find(:first)

(here, ordered by ID). As of Rails 2.1, though, there’s support to also get the last item:


last = Donation.find(:last)

As with first, it’s not restricted to just one object; you can use limits, conditions, etc. to get whatever set of objects you want (albeit from the end, not the beginning).

But notice, this is nothing new; just a convenience method, syntactic sugar. Check this code out:


bottom_ten = Donation.find(:limit => 10, :order => "id DESC")

This is, really, the same thing as:


bottom_ten = Donation.find(:last, :limit => 10)

But convenience and readability are always great goals!

And, a bonus gift–Rails 2.1 also allows you to more easily grab the first and last items! Instead of this:


first = Donation.find(:first)
last = Donation.find(:last)
all = Donation.find(:all)

You can write:

first = Donation.first
last = Donation.last
all = Donation.all

Same functionality! Easy as that.

As for why you’d need the last element, that’s another issue; perhaps, as in the case of donations, to calculate the range of days over which all donations were received, or something like that.

This is one of several topics discussed in the Rails 2.1 eBook.

About Ashiq Alibhai

Ashiq Alibhai, PMP, has been a Rails aficionado since 2007, and developed web applications since early 2003, where he learned PHP in one summer. As the driving-force behind RailsRocket and the Launchpad project, he seeks to share the ease of development with Rails far and wide.
This entry was posted in Development and tagged , , . Bookmark the permalink.

Comments are closed.