Merge pull request #47940 from fatkodima/fix-alias-where-missing

Remove table alias added when using `where.missing` or `where.associated`
This commit is contained in:
Rafael Mendonça França 2023-05-25 23:04:37 -04:00 committed by GitHub
commit 54ec908a2d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 20 additions and 2 deletions

@ -76,7 +76,11 @@ def associated(*associations)
associations.each do |association|
reflection = scope_association_reflection(association)
@scope.joins!(association)
self.not(association => { reflection.association_primary_key => nil })
if @scope.table_name == reflection.table_name
self.not(association => { reflection.association_primary_key => nil })
else
self.not(reflection.table_name => { reflection.association_primary_key => nil })
end
end
@scope
@ -104,7 +108,11 @@ def missing(*associations)
associations.each do |association|
reflection = scope_association_reflection(association)
@scope.left_outer_joins!(association)
@scope.where!(association => { reflection.association_primary_key => nil })
if @scope.table_name == reflection.table_name
@scope.where!(association => { reflection.association_primary_key => nil })
else
@scope.where!(reflection.table_name => { reflection.association_primary_key => nil })
end
end
@scope

@ -43,6 +43,10 @@ def test_associated_with_invalid_association_name
assert_match(/An association named `:cars` does not exist on the model `Post`\./, e.message)
end
def test_associated_merged_with_scope_on_association
assert_equal Author.find(1).posts.count, Post.where.associated(:author).merge(Author.where(id: 1)).count
end
def test_missing_with_association
assert posts(:authorless).author.blank?
assert_equal [posts(:authorless)], Post.where.missing(:author).to_a
@ -68,6 +72,12 @@ def test_missing_with_multiple_association
assert_equal [posts(:authorless)], Post.where.missing(:author, :comments).to_a
end
def test_missing_merged_with_scope_on_association
# This query does not make much logical sense, but it is testing
# that the generated SQL query is valid.
assert_equal Author.find(1).posts.count, Post.where.missing(:author).merge(Author.where(id: 1)).count
end
def test_not_inverts_where_clause
relation = Post.where.not(title: "hello")
expected_where_clause = Post.where(title: "hello").where_clause.invert