From a77dfdaa851cd67e4052e16e0d42a1656f0501a9 Mon Sep 17 00:00:00 2001 From: Lee Richmond Date: Mon, 19 Sep 2016 14:10:50 -0400 Subject: [PATCH] Ensure valid jsonapi when blank relationship (#1930) If you specify include_data false, and do not have any links for this relationship, we would output something like: `{ relationships: { comments: {} } }` This is not valid jsonapi. We will now render `{ relationships: { comments: { meta: {} } } }` Instead. Relevant jsonapi spec: http://jsonapi.org/format/#document-resource-object-relationships --- CHANGELOG.md | 1 + lib/active_model_serializers/adapter/json_api/relationship.rb | 1 + test/adapter/json_api/relationship_test.rb | 2 +- 3 files changed, 3 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index eb1173f0..f5a0b6d8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,7 @@ Fixes: - [#1887](https://github.com/rails-api/active_model_serializers/pull/1887) Make the comment reflect what the function does (@johnnymo87) - [#1890](https://github.com/rails-api/active_model_serializers/issues/1890) Ensure generator inherits from ApplicationSerializer when available (@richmolj) - [#1922](https://github.com/rails-api/active_model_serializers/pull/1922) Make railtie an optional dependency in runtime (@ggpasqualino) +- [#1930](https://github.com/rails-api/active_model_serializers/pull/1930) Ensure valid jsonapi when relationship has no links or data (@richmolj) Features: diff --git a/lib/active_model_serializers/adapter/json_api/relationship.rb b/lib/active_model_serializers/adapter/json_api/relationship.rb index 8cff36ef..0d34cf93 100644 --- a/lib/active_model_serializers/adapter/json_api/relationship.rb +++ b/lib/active_model_serializers/adapter/json_api/relationship.rb @@ -24,6 +24,7 @@ module ActiveModelSerializers meta = meta_for(association) hash[:meta] = meta if meta + hash[:meta] = {} if hash.empty? hash end diff --git a/test/adapter/json_api/relationship_test.rb b/test/adapter/json_api/relationship_test.rb index 5e4d016e..ed3a68c0 100644 --- a/test/adapter/json_api/relationship_test.rb +++ b/test/adapter/json_api/relationship_test.rb @@ -54,7 +54,7 @@ module ActiveModelSerializers end def test_relationship_data_not_included - test_relationship({}, options: { include_data: false }) + test_relationship({ meta: {} }, options: { include_data: false }) end def test_relationship_simple_link