How to get last N records with activerecord?

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

    For Rails 5 (and likely Rails 4)

    Bad:

    Something.last(5)
    

    because:

    Something.last(5).class
    => Array
    

    so:

    Something.last(50000).count
    

    will likely blow up your memory or take forever.

    Good approach:

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

    because:

    Something.limit(5).order('id desc').class
    => Image::ActiveRecord_Relation
    
    Something.limit(5).order('id desc').to_sql
    => "SELECT  \"somethings\".* FROM \"somethings\" ORDER BY id desc LIMIT 5"
    

    The latter is an unevaluated scope. You can chain it, or convert it to an array via .to_a. So:

    Something.limit(50000).order('id desc').count
    

    ... takes a second.

提交回复
热议问题