How to get last N records with activerecord?

前端 未结 14 657
南旧
南旧 2020-12-12 11:43

With :limit in query, I will get first N records. What is the easiest way to get last N records?

14条回答
  •  春和景丽
    2020-12-12 11:59

    Updated Answer (2020)

    You can get last N records simply by using last method:

    Record.last(N)

    Example:

    User.last(5)

    Returns 5 users in descending order by their id.

    Deprecated (Old Answer)

    An active record query like this I think would get you what you want ('Something' is the model name):

    Something.find(:all, :order => "id desc", :limit => 5).reverse
    

    edit: As noted in the comments, another way:

    result = Something.find(:all, :order => "id desc", :limit => 5)
    
    while !result.empty?
            puts result.pop
    end
    

提交回复
热议问题