ruby-on-rails rails most - How to get last N records with activerecord?
:limit in query, I will get first N records. What is the easiest way to get last N records?
Solution is here:
Since rails is lazy, it will eventually hit the database with SQL like: "SELECT
table ORDER BY
id DESC LIMIT 5".
For Rails 5 (and likely Rails 4)
Something.last(5).class => Array
will likely blow up your memory or take forever.
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
... takes a second.
In my rails
(rails 4.2) project, I use
Model.last(10) # get the last 10 record order by id
and it works.
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.