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..3b5d91184 100644 --- a/lib/active_model_serializers/adapter/json_api/relationship.rb +++ b/lib/active_model_serializers/adapter/json_api/relationship.rb @@ -22,8 +22,11 @@ def as_json links = links_for(association) hash[:links] = links if links.any? - meta = meta_for(association) - hash[:meta] = meta if meta + if meta = meta_for(association) + hash[:meta] = meta + else + hash[:meta] = {} if hash.empty? + end 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