Skip to content

Commit

Permalink
Make find_nth_from_last more performant when using reversible order
Browse files Browse the repository at this point in the history
We can use `relation.last(index)[-index]` instead of loading all records
when using reversible order because `last` will call `reverse_order`.
  • Loading branch information
kamipo committed Jan 7, 2018
1 parent 68754d3 commit f5328d9
Showing 1 changed file with 5 additions and 6 deletions.
11 changes: 5 additions & 6 deletions activerecord/lib/active_record/relation/finder_methods.rb
Original file line number Diff line number Diff line change
Expand Up @@ -547,12 +547,11 @@ def find_nth_from_last(index)
else
relation = ordered_relation

relation.to_a[-index]
# TODO: can be made more performant on large result sets by
# for instance, last(index)[-index] (which would require
# refactoring the last(n) finder method to make test suite pass),
# or by using a combination of reverse_order, limit, and offset,
# e.g., reverse_order.offset(index-1).first
if equal?(relation) || has_limit_or_offset?
relation.records[-index]
else
relation.last(index)[-index]
end
end
end

Expand Down

0 comments on commit f5328d9

Please sign in to comment.