Ruby on Rails: Selecting the last item in a database table

Ruby on Rails has the great find(:first) method that lets you grab the very first ActiveRecord object out of a given database table. That’s all well and good, but what if you want the last? Use this: Model.find(:first, :order => “id DESC”). That will give you the first record in a reversed list of IDs: basically, the record with the highest ID value, or the last record in the table.

Not good enough for you? Order by any other field. Want a different first record ? Sort by a field ASC. The :first record really depends on what order your records are in.

technorati tags:, , Ruby, Rails, ActiveRecord

2 Responses to “Ruby on Rails: Selecting the last item in a database table”
  1. Matt Buck Says:

    I know this is one of those things that I should have been able to figure out on my own, but for some reason I was having trouble. Thanks for the post!

  2. ajm Says:

    No problem! I’d figured I’d better share.

I'm Reading…
Search This Site

AddThis Feed Button

Need great hosting?

Categories