Skip to content

Commit 4026aba

Browse files
committed
This branch fixes the issues raised in rails#48862. By adding the key and it's values to self.references_values as Rails does when building a where clause, it prevents unneccessary aliasing from taking place and allows a User to successfully use a table_alias in their select query using a Hash.
1 parent a8871e6 commit 4026aba

File tree

2 files changed

+19
-0
lines changed

2 files changed

+19
-0
lines changed

activerecord/lib/active_record/relation/query_methods.rb

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2002,6 +2002,10 @@ def transform_select_hash_values(fields)
20022002
case columns_aliases
20032003
when Hash
20042004
columns_aliases.map do |column, column_alias|
2005+
if values[:joins]&.include?(key)
2006+
references = PredicateBuilder.references({ key.to_s => fields[key] })
2007+
self.references_values |= references unless references.empty?
2008+
end
20052009
arel_column("#{key}.#{column}") do
20062010
predicate_builder.resolve_arel_attribute(key.to_s, column)
20072011
end.as(column_alias.to_s)

activerecord/test/cases/relation/select_test.rb

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,21 @@ def test_select_with_hash_array_value_with_not_exists_field
4545
end
4646
end
4747

48+
def test_select_with_hash_and_table_alias
49+
post = Post.joins(:comments, :comments_with_extend)
50+
.select(
51+
:title,
52+
posts: { title: :post_title },
53+
comments: { body: :comment_body },
54+
comments_with_extend: { body: :comment_body_2 }
55+
)
56+
.take
57+
58+
assert_equal post.title, post.post_title
59+
assert_not_nil post.comment_body
60+
assert_not_nil post.comment_body_2
61+
end
62+
4863
def test_select_with_invalid_nested_field
4964
assert_raises(ActiveRecord::StatementInvalid) do
5065
Post.select(posts: { "UPPER(title)" => :post_title }).take

0 commit comments

Comments
 (0)