From f5328d9379da473bfc5420996693a14c6e0d2556 Mon Sep 17 00:00:00 2001 From: Ryuta Kamizono Date: Sun, 7 Jan 2018 14:05:02 +0900 Subject: Make `find_nth_from_last` more performant when using reversible order We can use `relation.last(index)[-index]` instead of loading all records when using reversible order because `last` will call `reverse_order`. --- activerecord/lib/active_record/relation/finder_methods.rb | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/activerecord/lib/active_record/relation/finder_methods.rb b/activerecord/lib/active_record/relation/finder_methods.rb index 4bf346a512..e61cacf6a7 100644 --- a/activerecord/lib/active_record/relation/finder_methods.rb +++ b/activerecord/lib/active_record/relation/finder_methods.rb @@ -547,12 +547,11 @@ module ActiveRecord 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 -- cgit v1.2.3