How to get last N records with activerecord?

前端 未结 14 651
南旧
南旧 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 11:57

    If you need to set some ordering on results then use:

    Model.order('name desc').limit(n) # n= number
    

    if you do not need any ordering, and just need records saved in the table then use:

    Model.last(n) # n= any number
    
    0 讨论(0)
  • 2020-12-12 11:59

    Updated Answer (2020)

    You can get last N records simply by using last method:

    Record.last(N)

    Example:

    User.last(5)

    Returns 5 users in descending order by their id.

    Deprecated (Old Answer)

    An active record query like this I think would get you what you want ('Something' is the model name):

    Something.find(:all, :order => "id desc", :limit => 5).reverse
    

    edit: As noted in the comments, another way:

    result = Something.find(:all, :order => "id desc", :limit => 5)
    
    while !result.empty?
            puts result.pop
    end
    
    0 讨论(0)
  • 2020-12-12 12:05

    new way to do it in rails 3.1 is SomeModel.limit(5).order('id desc')

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

    Let's say N = 5 and your model is Message, you can do something like this:

    Message.order(id: :asc).from(Message.all.order(id: :desc).limit(5), :messages)
    

    Look at the sql:

    SELECT "messages".* FROM (
      SELECT  "messages".* FROM "messages"  ORDER BY "messages"."created_at" DESC LIMIT 5
    ) messages  ORDER BY "messages"."created_at" ASC
    

    The key is the subselect. First we need to define what are the last messages we want and then we have to order them in ascending order.

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

    Solution is here:

    SomeModel.last(5).reverse
    

    Since rails is lazy, it will eventually hit the database with SQL like: "SELECT table.* FROM table ORDER BY table.id DESC LIMIT 5".

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

    0 讨论(0)
提交回复
热议问题