views:

831

answers:

3

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

A: 

Add an :order parameter to the query

frankodwyer
then I will get results in wrong order
JtR
+5  A: 

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
Dan McNevin
seems unnecessary to order the data twice, I'm currently getting the count first and using it with offset
JtR
That was the other method I was thinking of, but that seems like even more work since that's 2 queries against the database instead of 1. I guess I assume that you need to iterate over the array at some point, so you could let ruby sort it at at that time. (ie. records.reverse.each do ..)
Dan McNevin
Alternately, you could not reverse the array and use Array.pop to iterate over the array rather than reversing it.. http://www.ruby-doc.org/core-1.8.7/classes/Array.html#M000280
Dan McNevin
A: 

an other one solution

SomeModel.all.last(count).reverse
Bogdan Kulbida