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:rubyonrails, RoR, Ruby, Rails, ActiveRecord
November 14th, 2006 at 7:54 pm
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!
November 14th, 2006 at 10:01 pm
No problem! I’d figured I’d better share.