From c6a14c9eac5c3362e0fe9326dae40aa112ff75af Mon Sep 17 00:00:00 2001 From: Joe Meredith Date: Mon, 30 Oct 2017 08:33:31 -0400 Subject: [PATCH] Fail if collection type cannot be inferred with json adapter (#2210) --- CHANGELOG.md | 1 + lib/active_model/serializer/collection_serializer.rb | 5 ++++- test/collection_serializer_test.rb | 8 ++++++-- 3 files changed, 11 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index bccdece0..36b43922 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -17,6 +17,7 @@ Fixes: - [#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) - [#2200](https://github.com/rails-api/active_model_serializers/pull/2200) Fix deserialization of polymorphic relationships. (@dennis95stumm) +- [#2214](https://github.com/rails-api/active_model_serializers/pull/2214) Fail if unable to infer collection type with json adapter. (@jmeredith16) Misc: diff --git a/lib/active_model/serializer/collection_serializer.rb b/lib/active_model/serializer/collection_serializer.rb index 44b806a1..7a80a839 100644 --- a/lib/active_model/serializer/collection_serializer.rb +++ b/lib/active_model/serializer/collection_serializer.rb @@ -46,7 +46,10 @@ module ActiveModel # 3. get from collection name, if a named collection key ||= object.respond_to?(:name) ? object.name && object.name.underscore : nil # 4. key may be nil for empty collection and no serializer option - key && key.pluralize + key &&= key.pluralize + # 5. fail if the key cannot be determined + key || fail(ArgumentError, 'Cannot infer root key from collection type. Please + specify the root or each_serializer option, or render a JSON String') end # rubocop:enable Metrics/CyclomaticComplexity diff --git a/test/collection_serializer_test.rb b/test/collection_serializer_test.rb index cdbebb15..99157808 100644 --- a/test/collection_serializer_test.rb +++ b/test/collection_serializer_test.rb @@ -93,12 +93,16 @@ module ActiveModel resource = [] resource.define_singleton_method(:name) { nil } serializer = collection_serializer.new(resource) - assert_nil serializer.json_key + assert_raise ArgumentError do + serializer.json_key + end end def test_json_key_with_resource_without_name_and_no_serializers serializer = collection_serializer.new([]) - assert_nil serializer.json_key + assert_raise ArgumentError do + serializer.json_key + end end def test_json_key_with_empty_resources_with_serializer