How to get last N records with activerecord?

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

    I find that this query is better/faster for using the "pluck" method, which I love:

    Challenge.limit(5).order('id desc')
    

    This gives an ActiveRecord as the output; so you can use .pluck on it like this:

    Challenge.limit(5).order('id desc').pluck(:id)
    

    which quickly gives the ids as an array while using optimal SQL code.

提交回复
热议问题