aboutsummaryrefslogtreecommitdiffstats
path: root/activerecord
diff options
context:
space:
mode:
authorDamien Mathieu <42@dmathieu.com>2011-09-05 13:40:49 +0200
committerDamien Mathieu <42@dmathieu.com>2011-09-05 14:37:37 +0200
commit5f5527c726841cdefb82965a645d554767c5a6a9 (patch)
tree9988d58da2e27c67a6de9e01137f81b3dc9a6c9b /activerecord
parent451cdd62ce54080d0a4944551fbc3f10cc34a42d (diff)
downloadrails-5f5527c726841cdefb82965a645d554767c5a6a9.tar.gz
rails-5f5527c726841cdefb82965a645d554767c5a6a9.tar.bz2
rails-5f5527c726841cdefb82965a645d554767c5a6a9.zip
Use LIMIT sql word in last when it's possible
Diffstat (limited to 'activerecord')
-rw-r--r--activerecord/lib/active_record/relation/finder_methods.rb6
-rw-r--r--activerecord/test/cases/finder_test.rb19
2 files changed, 23 insertions, 2 deletions
diff --git a/activerecord/lib/active_record/relation/finder_methods.rb b/activerecord/lib/active_record/relation/finder_methods.rb
index 2639c46709..83d650d3f4 100644
--- a/activerecord/lib/active_record/relation/finder_methods.rb
+++ b/activerecord/lib/active_record/relation/finder_methods.rb
@@ -134,7 +134,11 @@ module ActiveRecord
def last(*args)
if args.any?
if args.first.kind_of?(Integer) || (loaded? && !args.first.kind_of?(Hash))
- to_a.last(*args)
+ if order_values.empty? && reorder_value.nil?
+ order("#{primary_key} DESC").limit(*args).reverse
+ else
+ to_a.last(*args)
+ end
else
apply_finder_options(args.first).last
end
diff --git a/activerecord/test/cases/finder_test.rb b/activerecord/test/cases/finder_test.rb
index fbcae27719..d840d38678 100644
--- a/activerecord/test/cases/finder_test.rb
+++ b/activerecord/test/cases/finder_test.rb
@@ -243,8 +243,25 @@ class FinderTest < ActiveRecord::TestCase
end
end
- def test_first_with_integer_should_use_sql_limit
+ def test_first_and_last_with_integer_should_use_sql_limit
assert_sql(/LIMIT 2/) { Topic.first(2).entries }
+ assert_sql(/LIMIT 5/) { Topic.last(5).entries }
+ end
+
+ def test_last_with_integer_and_order_should_keep_the_order
+ assert_equal Topic.order("title").to_a.last(2), Topic.order("title").last(2)
+ end
+
+ def test_last_with_integer_and_order_should_not_use_sql_limit
+ query = assert_sql { Topic.order("title").last(5).entries }
+ assert_equal 1, query.length
+ assert_no_match(/LIMIT/, query.first)
+ end
+
+ def test_last_with_integer_and_reorder_should_not_use_sql_limit
+ query = assert_sql { Topic.reorder("title").last(5).entries }
+ assert_equal 1, query.length
+ assert_no_match(/LIMIT/, query.first)
end
def test_first_and_last_with_integer_should_return_an_array