Skip to content

Commit

Permalink
This branch fixes the issues raised in rails#48862. By adding the key…
Browse files Browse the repository at this point in the history
… 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.
  • Loading branch information
paulreece committed Aug 25, 2023
1 parent a8871e6 commit 4026aba
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 0 deletions.
4 changes: 4 additions & 0 deletions activerecord/lib/active_record/relation/query_methods.rb
Original file line number Diff line number Diff line change
Expand Up @@ -2002,6 +2002,10 @@ def transform_select_hash_values(fields)
case columns_aliases
when Hash
columns_aliases.map do |column, column_alias|
if values[:joins]&.include?(key)
references = PredicateBuilder.references({ key.to_s => fields[key] })
self.references_values |= references unless references.empty?
end
arel_column("#{key}.#{column}") do
predicate_builder.resolve_arel_attribute(key.to_s, column)
end.as(column_alias.to_s)
Expand Down
15 changes: 15 additions & 0 deletions activerecord/test/cases/relation/select_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,21 @@ def test_select_with_hash_array_value_with_not_exists_field
end
end

def test_select_with_hash_and_table_alias
post = Post.joins(:comments, :comments_with_extend)
.select(
:title,
posts: { title: :post_title },
comments: { body: :comment_body },
comments_with_extend: { body: :comment_body_2 }
)
.take

assert_equal post.title, post.post_title
assert_not_nil post.comment_body
assert_not_nil post.comment_body_2
end

def test_select_with_invalid_nested_field
assert_raises(ActiveRecord::StatementInvalid) do
Post.select(posts: { "UPPER(title)" => :post_title }).take
Expand Down

0 comments on commit 4026aba

Please sign in to comment.