Skip to content

Commit 9a206a1

Browse files
author
Yohan Robert
authored
Remove nil relationships links (#1833)
1 parent 91b37ce commit 9a206a1

File tree

3 files changed

+14
-2
lines changed

3 files changed

+14
-2
lines changed

CHANGELOG.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,8 @@ Features:
88

99
Fixes:
1010

11+
- [#1833](https://github.com/rails-api/active_model_serializers/pull/1833) Remove relationship links if they are null (@groyoh)
12+
1113
Misc:
1214

1315
### [v0.10.2 (2016-07-05)](https://github.com/rails-api/active_model_serializers/compare/v0.10.1...v0.10.2)

lib/active_model_serializers/adapter/json_api/relationship.rb

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,8 @@ def initialize(parent_serializer, serializer, serializable_resource_options, arg
1313
@serializable_resource_options = serializable_resource_options
1414
@data = data_for(serializer)
1515
@links = args.fetch(:links, {}).each_with_object({}) do |(key, value), hash|
16-
hash[key] = ActiveModelSerializers::Adapter::JsonApi::Link.new(parent_serializer, value).as_json
16+
result = Link.new(parent_serializer, value).as_json
17+
hash[key] = result if result
1718
end
1819
meta = args.fetch(:meta, nil)
1920
@meta = meta.respond_to?(:call) ? parent_serializer.instance_eval(&meta) : meta

test/adapter/json_api/relationships_test.rb

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,8 +13,9 @@ class RelationshipAuthorSerializer < ActiveModel::Serializer
1313
end
1414

1515
has_one :profile do
16+
id = object.profile.id
1617
link :related do
17-
"//example.com/profiles/#{object.profile.id}"
18+
"//example.com/profiles/#{id}" if id != 123
1819
end
1920
end
2021

@@ -113,6 +114,14 @@ def test_relationship_block_link
113114
assert_relationship(:profile, expected)
114115
end
115116

117+
def test_relationship_nil_link
118+
@author.profile.id = 123
119+
expected = {
120+
data: { id: '123', type: 'profiles' }
121+
}
122+
assert_relationship(:profile, expected)
123+
end
124+
116125
def test_relationship_block_link_href
117126
expected = {
118127
data: [{ id: '1337', type: 'locations' }],

0 commit comments

Comments
 (0)