diff options
author | Ryuta Kamizono <kamipo@gmail.com> | 2018-01-07 14:05:02 +0900 |
---|---|---|
committer | Ryuta Kamizono <kamipo@gmail.com> | 2018-01-07 14:31:18 +0900 |
commit | f5328d9379da473bfc5420996693a14c6e0d2556 (patch) | |
tree | bfba992eca2f23b93760e248b6a19035dbef5780 /activerecord | |
parent | 68754d37706f11ca363b3108eda10749b9957817 (diff) | |
download | rails-f5328d9379da473bfc5420996693a14c6e0d2556.tar.gz rails-f5328d9379da473bfc5420996693a14c6e0d2556.tar.bz2 rails-f5328d9379da473bfc5420996693a14c6e0d2556.zip |
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`.
Diffstat (limited to 'activerecord')
-rw-r--r-- | activerecord/lib/active_record/relation/finder_methods.rb | 11 |
1 files 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 |