diff options
Diffstat (limited to 'activerecord')
-rw-r--r-- | activerecord/CHANGELOG.md | 5 | ||||
-rw-r--r-- | activerecord/lib/active_record/relation/finder_methods.rb | 4 | ||||
-rw-r--r-- | activerecord/test/cases/finder_test.rb | 14 |
3 files changed, 21 insertions, 2 deletions
diff --git a/activerecord/CHANGELOG.md b/activerecord/CHANGELOG.md index 5abc84d3fb..5651783092 100644 --- a/activerecord/CHANGELOG.md +++ b/activerecord/CHANGELOG.md @@ -1,4 +1,9 @@ ## unreleased ## +* Fix `FinderMethods#last` unscoped primary key. + + Fixes #11917. + + *Eugene Kalenkovich* * Load fixtures from linked folders. diff --git a/activerecord/lib/active_record/relation/finder_methods.rb b/activerecord/lib/active_record/relation/finder_methods.rb index cdf18f8080..1efe4dbfde 100644 --- a/activerecord/lib/active_record/relation/finder_methods.rb +++ b/activerecord/lib/active_record/relation/finder_methods.rb @@ -134,8 +134,8 @@ module ActiveRecord def last(*args) if args.any? if args.first.kind_of?(Integer) || (loaded? && !args.first.kind_of?(Hash)) - if order_values.empty? - order("#{primary_key} DESC").limit(*args).reverse + if order_values.empty? && primary_key + order("#{quoted_table_name}.#{quoted_primary_key} DESC").limit(*args).reverse else to_a.last(*args) end diff --git a/activerecord/test/cases/finder_test.rb b/activerecord/test/cases/finder_test.rb index 2efafe5c24..89e17643f6 100644 --- a/activerecord/test/cases/finder_test.rb +++ b/activerecord/test/cases/finder_test.rb @@ -305,10 +305,24 @@ class FinderTest < ActiveRecord::TestCase assert_sql(/LIMIT 5|ROWNUM <= 5/) { Topic.last(5).entries } end + def test_last_should_use_default_order + assert_sql(/ORDER BY .topics.\..id. DESC/) { Topic.last } + end + + def test_last_with_integer_should_use_default_order + assert_sql(/ORDER BY .topics.\..id. DESC/) { 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_should_work_with_joins + assert_nothing_raised do + Post.joins(:comments).last(2) + end + 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 |