Rails:如何在最后之前找到记录?

[英]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:

我可以在下面的例子中找到我表格中的最后一条记录,但如果我想在最后一次找到记录,例如(last-1)或(last-2)..?我在每个循环中都有这个例子:

Table.find(:last, :conditions => {:dogovor_id => p.id}).id

4 个解决方案

#1


20  

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

#2


18  

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

另一种更容易记住的方法是:Model.last(2).first

#3


2  

You can use negative indices.

您可以使用负指数。

The second-to-last element has index -2:

倒数第二个元素的索引为-2:

Model.all[-2]

The 10th to last:

第10到最后:

Model.all[-10]

In Rails 5 the penultimate forms for [-2] and [-3] have aliases. So if you want, use this:

在Rails 5中,[-2]和[-3]的倒数第二个形式具有别名。所以,如果你想,请使用:

Model.second_to_last
Model.third_to_last

#4


0  

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:

'first'方法是一个数组方法,所以关于性能,最好使用'limit'方法,这是一个ActiveRecord方法并将LIMIT子句附加到SQL查询:

Table.where(dogovor_id: p.id).order(id: :desc).offset(1).limit(1) # last - 1

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:http://www.itdaan.com/blog/2011/08/10/f21b9c1d5c8cbf9a2d3fb42821dbd6b9.html



 
© 2014-2018 ITdaan.com 粤ICP备14056181号