How to get last N records with activerecord?

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

    In my rails (rails 4.2) project, I use

    Model.last(10) # get the last 10 record order by id
    

    and it works.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-12 12:21

    Add an :order parameter to the query

    0 讨论(0)
  • 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)
    
    0 讨论(0)
  • 2020-12-12 12:24

    This is the Rails 3 way

    SomeModel.last(5) # last 5 records in ascending order
    
    SomeModel.last(5).reverse # last 5 records in descending order
    
    0 讨论(0)
  • 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|
    
    0 讨论(0)
提交回复
热议问题