How to get last N records with activerecord?

前端 未结 14 683
南旧
南旧 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 12:24

    For Rails 4 and above version:

    You can try something like this If you want first oldest entry

    YourModel.order(id: :asc).limit(5).each do |d|
    

    You can try something like this if you want last latest entries..

    YourModel.order(id: :desc).limit(5).each do |d|
    

提交回复
热议问题