Rails: how to find record before last?

后端 未结 4 1402
感情败类
感情败类 2021-01-01 12:52

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:

4条回答
  •  鱼传尺愫
    2021-01-01 13:11

    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
    

提交回复
热议问题