1
0
Fork 0
mirror of https://github.com/rails/rails.git synced 2022-11-09 12:12:34 -05:00

Merge pull request #44000 from ykpythemind/better_message_for_missing

Better error messages when association name is invalid in the argument of `ActiveRecord::QueryMethods::WhereChain#missing`
This commit is contained in:
Rafael Mendonça França 2022-01-05 15:54:58 -05:00 committed by GitHub
commit ce2ee21b9c
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 11 additions and 0 deletions

View file

@ -97,6 +97,9 @@ module ActiveRecord
def missing(*associations)
associations.each do |association|
reflection = @scope.klass._reflect_on_association(association)
unless reflection
raise ArgumentError.new("An association named `:#{association}` does not exist on the model `#{@scope.name}`.")
end
@scope.left_outer_joins!(association)
@scope.where!(reflection.table_name => { reflection.association_primary_key => nil })
end

View file

@ -33,6 +33,14 @@ module ActiveRecord
assert_equal [posts(:authorless)], Post.where.missing(:author).to_a
end
def test_missing_with_invalid_association_name
e = assert_raises(ArgumentError) do
Post.where.missing(:cars).to_a
end
assert_match(/An association named `:cars` does not exist on the model `Post`\./, e.message)
end
def test_missing_with_multiple_association
assert posts(:authorless).comments.empty?
assert_equal [posts(:authorless)], Post.where.missing(:author, :comments).to_a