Skip to content

Commit 00a1410

Browse files
committed
Improve invalid argument error for with
Currently `with` requires a hash as an argument, if invalid argument is passed, it will raise NoMethodError in `process_with_args`. This improves that will raise ArgumentError rather than NoMethodError.
1 parent 0e3e0d1 commit 00a1410

File tree

2 files changed

+7
-2
lines changed

2 files changed

+7
-2
lines changed

activerecord/lib/active_record/relation/query_methods.rb

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1909,8 +1909,6 @@ def build_with(arel)
19091909
return if with_values.empty?
19101910

19111911
with_statements = with_values.map do |with_value|
1912-
raise ArgumentError, "Unsupported argument type: #{with_value} #{with_value.class}" unless with_value.is_a?(Hash)
1913-
19141912
build_with_value_from_hash(with_value)
19151913
end
19161914

@@ -2243,6 +2241,7 @@ def arel_column_aliases_from_hash(fields)
22432241

22442242
def process_with_args(args)
22452243
args.flat_map do |arg|
2244+
raise ArgumentError, "Unsupported argument type: #{arg} #{arg.class}" unless arg.is_a?(Hash)
22462245
arg.map { |k, v| { k => v } }
22472246
end
22482247
end

activerecord/test/cases/relation/with_test.rb

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,12 @@ def test_with_when_hash_with_multiple_elements_of_different_type_is_passed_as_an
3636
assert_equal POSTS_WITH_TAGS_AND_MULTIPLE_COMMENTS, relation.order(:id).pluck(:id)
3737
end
3838

39+
def test_with_when_invalid_argument_is_passed
40+
assert_raises ArgumentError, match: /\AUnsupported argument type: #<Post:0x[0-9a-f]+> Post\z/ do
41+
Post.with(Post.where("tags_count > 0"))
42+
end
43+
end
44+
3945
def test_multiple_with_calls
4046
relation = Post
4147
.with(posts_with_tags: Post.where("tags_count > 0"))

0 commit comments

Comments
 (0)