How to get last N records with activerecord?

前端 未结 14 665
南旧
南旧 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:23

    If you have a default scope in your model that specifies an ascending order in Rails 3 you'll need to use reorder rather than order as specified by Arthur Neves above:

    Something.limit(5).reorder('id desc')
    

    or

    Something.reorder('id desc').limit(5)
    

提交回复
热议问题