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.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
Rails 4:
Model.last(2).first
In Rails 5+ you can use new self-explanatory accessor methods:
Model.second_to_last
Model.third_to_last
You can also use negative indices.
Second to last:
Model.all[-2]
The 10th to last:
Model.all[-10]
NB: As pointed by @AndrewSchwartz, this method can be more problematic (consuming) on large tables. This method first loads all the records and then processes them, whereas second_to_last
generates more optimized query with LIMIT and OFFSET
Even if accepted answer works:
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
'first' method is an array method, so concerning performance its better to use 'limit' method which is an ActiveRecord method and attaches LIMIT clause to SQL query:
Table.where(dogovor_id: p.id).order(id: :desc).offset(1).limit(1) # last - 1
Another easier to remember way is: Model.last(2).first