How to get last N records with activerecord?

Viewed 160697

With :limit in query, I will get first N records. What is the easiest way to get last N records?

15 Answers

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

we can use Model.last(5) or Model.limit(5).order(id: :desc) in rails 5.2

A simple answer would be:

Model.limit(5).order(id: :desc)

There is a problem with this solution, as id can't be the sole determiner of when a record was created in the time.

A more reliable solution would be:

Model.order(created_at: :desc).limit(5)

As others have pointed out, one can also use Model.last(5). The only gotcha with this is that it returns Array, and not Model::ActiveRecord_Relation.

Add an :order parameter to the query

Related