Skip to content

Commit 110d365

Browse files
authored
Merge pull request rails#42782 from intrip/fix-eager-loading-with-order-hash
Fix `eager_loading?` when ordering with `Hash` syntax
2 parents ebebb9d + 8ab892e commit 110d365

File tree

3 files changed

+40
-1
lines changed

3 files changed

+40
-1
lines changed

activerecord/CHANGELOG.md

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,15 @@
1+
* Fix `eager_loading?` when ordering with `Hash` syntax
2+
3+
`eager_loading?` is triggered correctly when using `order` with hash syntax
4+
on an outer table.
5+
6+
```ruby
7+
Post.includes(:comments).order({ "comments.label": :ASC }).eager_loading?
8+
=> true
9+
```
10+
11+
*Jacopo Beschi*
12+
113
* Move the forcing of clear text encoding to the `ActiveRecord::Encryption::Encryptor`.
214

315
Fixes #42699.

activerecord/lib/active_record/relation/query_methods.rb

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1548,7 +1548,14 @@ def sanitize_order_arguments(order_args)
15481548
end
15491549

15501550
def column_references(order_args)
1551-
references = order_args.grep(String)
1551+
references = order_args.flat_map do |arg|
1552+
case arg
1553+
when String
1554+
arg
1555+
when Hash
1556+
arg.keys
1557+
end
1558+
end
15521559
references.map! { |arg| arg =~ /^\W?(\w+)\W?\./ && $1 }.compact!
15531560
references
15541561
end

activerecord/test/cases/relations_test.rb

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1704,6 +1704,26 @@ def test_references_doesnt_trigger_eager_loading_if_reference_not_included
17041704
assert_not_predicate scope, :eager_loading?
17051705
end
17061706

1707+
def test_order_triggers_eager_loading
1708+
scope = Post.includes(:comments).order("comments.label ASC")
1709+
assert_predicate scope, :eager_loading?
1710+
end
1711+
1712+
def test_order_doesnt_trigger_eager_loading_when_ordering_using_the_owner_table
1713+
scope = Post.includes(:comments).order("posts.title ASC")
1714+
assert_not_predicate scope, :eager_loading?
1715+
end
1716+
1717+
def test_order_triggers_eager_loading_when_ordering_using_hash_syntax
1718+
scope = Post.includes(:comments).order({ "comments.label": :ASC })
1719+
assert_predicate scope, :eager_loading?
1720+
end
1721+
1722+
def test_order_doesnt_trigger_eager_loading_when_ordering_using_the_owner_table_and_hash_syntax
1723+
scope = Post.includes(:comments).order({ "posts.title": :ASC })
1724+
assert_not_predicate scope, :eager_loading?
1725+
end
1726+
17071727
def test_automatically_added_where_references
17081728
scope = Post.where(comments: { body: "Bla" })
17091729
assert_equal ["comments"], scope.references_values

0 commit comments

Comments
 (0)