With :limit in query I will get first N records. What is the easiest way to get last N records?
then I will get results in wrong order
JtR
2009-01-07 14:11:28
+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
2009-01-07 14:07:43
seems unnecessary to order the data twice, I'm currently getting the count first and using it with offset
JtR
2009-01-07 14:12:32
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
2009-01-07 14:25:52
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
2009-01-07 14:33:46