From 3a9d372a07ea8c0241676cfc1cf9c2f5e327d34f Mon Sep 17 00:00:00 2001 From: Lee Richmond Date: Fri, 16 Sep 2016 14:31:10 -0400 Subject: [PATCH] Ensure valid jsonapi when blank relationship 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 eb1173f07..f5a0b6d83 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 8cff36eff..0d34cf937 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 @@ def as_json 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 5e4d016e6..ed3a68c0b 100644 --- a/test/adapter/json_api/relationship_test.rb +++ b/test/adapter/json_api/relationship_test.rb @@ -54,7 +54,7 @@ def test_relationship_with_data_array 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