Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: how to find record before last?

I can find last record in my table like in example below, but what if I want to find record before last, e.g. (last-1) or (last-2)..? I have this example in my each loop:

Table.find(:last, :conditions => {:dogovor_id => p.id}).id
like image 858
Oleg Pasko Avatar asked Aug 10 '11 17:08

Oleg Pasko


2 Answers

Another easier to remember way is: Model.last(2).first

like image 168
Juan Avatar answered Oct 02 '22 22:10

Juan


Table.where(:dogovor_id => p.id).order("id DESC").first           # last
Table.where(:dogovor_id => p.id).order("id DESC").offset(1).first # last - 1
Table.where(:dogovor_id => p.id).order("id DESC").offset(2).first # last - 2
like image 34
fl00r Avatar answered Oct 02 '22 23:10

fl00r