JtR JtR - 7 months ago 14
Ruby Question

How to get last N records with activerecord?

With

:limit
in query, I will get first N records. What is the easiest way to get last N records?

Answer

An active record query like this I think would get you what you want ('Something' is the model name):

Something.find(:all, :order => "id desc", :limit => 5).reverse

edit: As noted in the comments, another way:

result = Something.find(:all, :order => "id desc", :limit => 5)

while !result.empty?
        puts result.pop
end