ruby on rails - Whats the best way to get the nth to last record? -


i saw here: how last n records activerecord? best way last 5 records somemodel.last(5). best way 5th last record somemodel.last(5).first or else?

thanks in advance!

what you're looking combination of limit, offset, , ensuring query using order by constraint. described on postgresql - queries: limit , offset documentation page.

an example is:

irb> somemodel.count => 35  irb> somemodel.order(:id).reverse_order.limit(1).offset(4) # somemodel load (0.7ms)  select "some_models".* "some_models" order "some_models".id desc limit 1 offset 4 => #<activerecord::relation [#<somemodel id: 31, name: "hello world", created_at: "2014-03-24 21:52:46", updated_at: "2014-03-24 21:52:46">]> 

which yields same result (albeit ar::relation) as:

irb> somemodels.last(5).first # select "some_models".* "some_models" order "some_models"."id" desc limit 5 => #<somemodel id: 31, name: "hello world", created_at: "2014-03-24 21:52:46", updated_at: "2014-03-24 21:52:46"> 

the difference in former query, postgresql treat .reverse_order.limit.offset query in memory, , restrict values appropriately before returns result. in latter, postgresql return 5 results, , restrict values in ruby using #first.


Comments

Popular posts from this blog

android - Get AccessToken using signpost OAuth without opening a browser (Two legged Oauth) -

org.mockito.exceptions.misusing.InvalidUseOfMatchersException: mockito -

google shop client API returns 400 bad request error while adding an item -