Fix FinderMethods#last unscoped primary key

Fixes table.joins(:relation).last(N) breaking on sqlite

Conflicts:
	activerecord/CHANGELOG.md
	activerecord/test/cases/finder_test.rb
This commit is contained in:
Eugene Kalenkovich
2013-08-21 14:39:39 -07:00
committed by Rafael Mendonça França
parent cff8d1d24d
commit c9642e31b1
4 changed files with 21 additions and 3 deletions

View File

@@ -12,7 +12,6 @@
*Kassio Borges*
* Fix `ActionDispatch::Assertions::ResponseAssertions#assert_redirected_to`
does not show user-supplied message.

View File

@@ -1,4 +1,9 @@
## unreleased ##
* Fix `FinderMethods#last` unscoped primary key.
Fixes #11917.
*Eugene Kalenkovich*
* Load fixtures from linked folders.

View File

@@ -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

View File

@@ -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