Skip to content

Commit f5355a2

Browse files
authored
Merge pull request rails#51219 from mylesboone/order_references_arel_attribute
[Fix rails#49999] properly reference from Arel::Attribute args
2 parents 5cb2603 + e0c2363 commit f5355a2

File tree

2 files changed

+23
-9
lines changed

2 files changed

+23
-9
lines changed

activerecord/lib/active_record/relation/query_methods.rb

Lines changed: 21 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -2081,17 +2081,29 @@ def column_references(order_args)
20812081
order_args.flat_map do |arg|
20822082
case arg
20832083
when String, Symbol
2084-
arg
2084+
extract_table_name_from(arg)
20852085
when Hash
2086-
arg.keys.select { |e| e.is_a?(String) || e.is_a?(Symbol) }
2086+
arg
2087+
.map do |key, value|
2088+
case value
2089+
when Hash
2090+
key.to_s
2091+
else
2092+
extract_table_name_from(key) if key.is_a?(String) || key.is_a?(Symbol)
2093+
end
2094+
end
2095+
when Arel::Attribute
2096+
arg.relation.name
2097+
when Arel::Nodes::Ordering
2098+
if arg.expr.is_a?(Arel::Attribute)
2099+
arg.expr.relation.name
2100+
end
20872101
end
2088-
end.filter_map do |arg|
2089-
arg =~ /^\W?(\w+)\W?\./ && $1
2090-
end +
2091-
order_args
2092-
.select { |e| e.is_a?(Hash) }
2093-
.flat_map { |e| e.map { |k, v| k if v.is_a?(Hash) } }
2094-
.compact
2102+
end.compact
2103+
end
2104+
2105+
def extract_table_name_from(string)
2106+
string.match(/^\W?(\w+)\W?\./) && $1
20952107
end
20962108

20972109
def order_column(field)

activerecord/test/cases/relation/order_test.rb

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -55,11 +55,13 @@ def test_order_with_association
5555
assert_equal(author_then_book_name, Book.includes(:author).order("authors.name", books: { name: :asc }))
5656
assert_equal(author_then_book_name, Book.includes(:author).order("authors.name", "books.name"))
5757
assert_equal(author_then_book_name, Book.includes(:author).order({ authors: { name: :asc } }, Book.arel_table[:name]))
58+
assert_equal(author_then_book_name, Book.includes(:author).order(Author.arel_table[:name], Book.arel_table[:name]))
5859

5960
author_desc_then_book_name = [y, x, z]
6061

6162
assert_equal(author_desc_then_book_name, Book.includes(:author).order(authors: { name: :desc }, books: { name: :asc }))
6263
assert_equal(author_desc_then_book_name, Book.includes(:author).order("authors.name desc", books: { name: :asc }))
64+
assert_equal(author_desc_then_book_name, Book.includes(:author).order(Author.arel_table[:name].desc, books: { name: :asc }))
6365
assert_equal(author_desc_then_book_name, Book.includes(:author).order({ authors: { name: :desc } }, :name))
6466
end
6567
end

0 commit comments

Comments
 (0)