Skip to content

Commit 54d40c7

Browse files
authored
Merge pull request #2214 from jmeredith16/undeterminable-json-root
Fail if collection type cannot be inferred with json adapter (#2210)
2 parents 4076a48 + c6a14c9 commit 54d40c7

File tree

3 files changed

+11
-3
lines changed

3 files changed

+11
-3
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ Fixes:
1717

1818
- [#2022](https://github.com/rails-api/active_model_serializers/pull/2022) Mutation of ActiveModelSerializers::Model now changes the attributes. Originally in [#1984](https://github.com/rails-api/active_model_serializers/pull/1984). (@bf4)
1919
- [#2200](https://github.com/rails-api/active_model_serializers/pull/2200) Fix deserialization of polymorphic relationships. (@dennis95stumm)
20+
- [#2214](https://github.com/rails-api/active_model_serializers/pull/2214) Fail if unable to infer collection type with json adapter. (@jmeredith16)
2021

2122
Misc:
2223

lib/active_model/serializer/collection_serializer.rb

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,10 @@ def json_key
4646
# 3. get from collection name, if a named collection
4747
key ||= object.respond_to?(:name) ? object.name && object.name.underscore : nil
4848
# 4. key may be nil for empty collection and no serializer option
49-
key && key.pluralize
49+
key &&= key.pluralize
50+
# 5. fail if the key cannot be determined
51+
key || fail(ArgumentError, 'Cannot infer root key from collection type. Please
52+
specify the root or each_serializer option, or render a JSON String')
5053
end
5154
# rubocop:enable Metrics/CyclomaticComplexity
5255

test/collection_serializer_test.rb

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -93,12 +93,16 @@ def test_json_key_with_resource_with_nil_name_and_no_serializers
9393
resource = []
9494
resource.define_singleton_method(:name) { nil }
9595
serializer = collection_serializer.new(resource)
96-
assert_nil serializer.json_key
96+
assert_raise ArgumentError do
97+
serializer.json_key
98+
end
9799
end
98100

99101
def test_json_key_with_resource_without_name_and_no_serializers
100102
serializer = collection_serializer.new([])
101-
assert_nil serializer.json_key
103+
assert_raise ArgumentError do
104+
serializer.json_key
105+
end
102106
end
103107

104108
def test_json_key_with_empty_resources_with_serializer

0 commit comments

Comments
 (0)