Rails: how to find record before last? Rails: how to find record before last? ruby-on-rails ruby-on-rails

Rails: how to find record before last?


Table.where(:dogovor_id => p.id).order("id DESC").first           # lastTable.where(:dogovor_id => p.id).order("id DESC").offset(1).first # last - 1Table.where(:dogovor_id => p.id).order("id DESC").offset(2).first # last - 2


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


Rails 4:

Model.last(2).first

In Rails 5+ you can use new self-explanatory accessor methods:

Model.second_to_lastModel.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