properly reference tables from Arel in #order

This commit is contained in:
Myles Boone 2024-06-13 00:00:27 -04:00
parent 827f4ef15c
commit e0c2363d9a
2 changed files with 23 additions and 9 deletions

@ -2081,17 +2081,29 @@ def column_references(order_args)
order_args.flat_map do |arg|
case arg
when String, Symbol
arg
extract_table_name_from(arg)
when Hash
arg.keys.select { |e| e.is_a?(String) || e.is_a?(Symbol) }
arg
.map do |key, value|
case value
when Hash
key.to_s
else
extract_table_name_from(key) if key.is_a?(String) || key.is_a?(Symbol)
end
end
when Arel::Attribute
arg.relation.name
when Arel::Nodes::Ordering
if arg.expr.is_a?(Arel::Attribute)
arg.expr.relation.name
end
end
end.filter_map do |arg|
arg =~ /^\W?(\w+)\W?\./ && $1
end +
order_args
.select { |e| e.is_a?(Hash) }
.flat_map { |e| e.map { |k, v| k if v.is_a?(Hash) } }
.compact
end.compact
end
def extract_table_name_from(string)
string.match(/^\W?(\w+)\W?\./) && $1
end
def order_column(field)

@ -55,11 +55,13 @@ def test_order_with_association
assert_equal(author_then_book_name, Book.includes(:author).order("authors.name", books: { name: :asc }))
assert_equal(author_then_book_name, Book.includes(:author).order("authors.name", "books.name"))
assert_equal(author_then_book_name, Book.includes(:author).order({ authors: { name: :asc } }, Book.arel_table[:name]))
assert_equal(author_then_book_name, Book.includes(:author).order(Author.arel_table[:name], Book.arel_table[:name]))
author_desc_then_book_name = [y, x, z]
assert_equal(author_desc_then_book_name, Book.includes(:author).order(authors: { name: :desc }, books: { name: :asc }))
assert_equal(author_desc_then_book_name, Book.includes(:author).order("authors.name desc", books: { name: :asc }))
assert_equal(author_desc_then_book_name, Book.includes(:author).order(Author.arel_table[:name].desc, books: { name: :asc }))
assert_equal(author_desc_then_book_name, Book.includes(:author).order({ authors: { name: :desc } }, :name))
end
end