aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--actionpack/CHANGELOG.md1
-rw-r--r--activerecord/CHANGELOG.md5
-rw-r--r--activerecord/lib/active_record/relation/finder_methods.rb4
-rw-r--r--activerecord/test/cases/finder_test.rb14
4 files changed, 21 insertions, 3 deletions
diff --git a/actionpack/CHANGELOG.md b/actionpack/CHANGELOG.md
index 1849803294..906592874d 100644
--- a/actionpack/CHANGELOG.md
+++ b/actionpack/CHANGELOG.md
@@ -12,7 +12,6 @@
*Kassio Borges*
-
* Fix `ActionDispatch::Assertions::ResponseAssertions#assert_redirected_to`
does not show user-supplied message.
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