Last active
November 5, 2015 16:48
-
-
Save austra/9ba13748bdad60da712f to your computer and use it in GitHub Desktop.
activerecord - .endmost scope - optimized .last
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
.endmost is what you want when you call .last: the last N records in the result set without having to retrieve all records from the database, and it works with any ordering. You can impose filtering before, Message.where(…).in_order.endmost(10), and afterwards to filter your final results as well Message.in_order.endmost(10).where(…). | |
class Message | |
class << self | |
def in_order | |
order(created_at: :asc) | |
end | |
def recent(n) | |
in_order.endmost(n) | |
end | |
def endmost(n) | |
all.only(:order).from(all.reverse_order.limit(n), table_name) | |
end | |
end | |
end | |
http://www.elabs.se/blog/72-retrieving-the-last-n-ordered-records-with-activerecord |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment