Rails: how to find record before last?

后端 未结 4 1379
感情败类
感情败类 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 12:57
    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
    
    0 讨论(0)
  • 2021-01-01 13:07

    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

    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2021-01-01 13:16

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

    0 讨论(0)
提交回复
热议问题