aboutsummaryrefslogtreecommitdiffstats
path: root/activerecord/lib/active_record/relation/finder_methods.rb
diff options
context:
space:
mode:
authorBogdan Gusiev <agresso@gmail.com>2016-01-28 17:45:53 +0200
committerBogdan Gusiev <agresso@gmail.com>2016-01-28 17:45:53 +0200
commit7705fcf0b6c0a1217fa91a709dcf00701f4af694 (patch)
tree76ed5d684c299be8ceaa054b86ea6a93fcc6025e /activerecord/lib/active_record/relation/finder_methods.rb
parent2637fb75d82e1c69333855abd58c2470994995d3 (diff)
downloadrails-7705fcf0b6c0a1217fa91a709dcf00701f4af694.tar.gz
rails-7705fcf0b6c0a1217fa91a709dcf00701f4af694.tar.bz2
rails-7705fcf0b6c0a1217fa91a709dcf00701f4af694.zip
Reworked ActiveRecord::Relation#last to always use SQL
instead of loading relation
Diffstat (limited to 'activerecord/lib/active_record/relation/finder_methods.rb')
-rw-r--r--activerecord/lib/active_record/relation/finder_methods.rb39
1 files changed, 17 insertions, 22 deletions
diff --git a/activerecord/lib/active_record/relation/finder_methods.rb b/activerecord/lib/active_record/relation/finder_methods.rb
index 3f5d6de78a..5d4a045097 100644
--- a/activerecord/lib/active_record/relation/finder_methods.rb
+++ b/activerecord/lib/active_record/relation/finder_methods.rb
@@ -145,15 +145,23 @@ module ActiveRecord
#
# [#<Person id:4>, #<Person id:3>, #<Person id:2>]
def last(limit = nil)
- if limit
- if order_values.empty? && primary_key
- order(arel_table[primary_key].desc).limit(limit).reverse
- else
- to_a.last(limit)
- end
- else
- find_last
- end
+ return find_last(limit) if loaded?
+
+ result = order_values.empty? && primary_key ? order(arel_table[primary_key].desc) : reverse_order
+ result = result.limit!(limit || 1)
+ limit ? result.reverse : result.first
+ rescue ActiveRecord::IrreversibleOrderError
+ ActiveSupport::Deprecation.warn(<<-WARNING.squish)
+ Finding a last element by loading the relation when SQL ORDER
+ can not be reversed is deprecated.
+ Rails 5.1 will raise ActiveRecord::IrreversibleOrderError in this case.
+ Please call `to_a.last` if you still want to load the relation.
+ WARNING
+ find_last(limit)
+ end
+
+ def find_last(limit)
+ limit ? to_a.last(limit) : to_a.last
end
# Same as #last but raises ActiveRecord::RecordNotFound if no record
@@ -523,19 +531,6 @@ module ActiveRecord
relation.limit(limit).to_a
end
- def find_last
- if loaded?
- @records.last
- else
- @last ||=
- if limit_value
- to_a.last
- else
- reverse_order.limit(1).to_a.first
- end
- end
- end
-
private
def find_nth_with_limit_and_offset(index, limit, offset:) # :nodoc: