Skip to content

Commit f9410db

Browse files
author
Lee Richmond
committed
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
1 parent a032201 commit f9410db

File tree

3 files changed

+8
-2
lines changed

3 files changed

+8
-2
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ Fixes:
99
- [#1887](https://github.com/rails-api/active_model_serializers/pull/1887) Make the comment reflect what the function does (@johnnymo87)
1010
- [#1890](https://github.com/rails-api/active_model_serializers/issues/1890) Ensure generator inherits from ApplicationSerializer when available (@richmolj)
1111
- [#1922](https://github.com/rails-api/active_model_serializers/pull/1922) Make railtie an optional dependency in runtime (@ggpasqualino)
12+
- [#1930](https://github.com/rails-api/active_model_serializers/pull/1930) Ensure valid jsonapi when relationship has no links or data (@richmolj)
1213

1314
Features:
1415

lib/active_model_serializers/adapter/json_api/relationship.rb

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ def as_json
2525
meta = meta_for(association)
2626
hash[:meta] = meta if meta
2727

28-
hash
28+
ensure_valid!(hash)
2929
end
3030

3131
protected
@@ -34,6 +34,11 @@ def as_json
3434

3535
private
3636

37+
def ensure_valid!(json)
38+
json[:meta] = {} if json.empty?
39+
json
40+
end
41+
3742
def data_for(association)
3843
serializer = association.serializer
3944
if serializer.respond_to?(:each)

test/adapter/json_api/relationship_test.rb

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,7 @@ def test_relationship_with_data_array
5454
end
5555

5656
def test_relationship_data_not_included
57-
test_relationship({}, options: { include_data: false })
57+
test_relationship({ meta: {} }, options: { include_data: false })
5858
end
5959

6060
def test_relationship_simple_link

0 commit comments

Comments
 (0)