Skip to content

Commit 1d7d9fd

Browse files
committed
Fix nested include attributes
When the requests asked for a nested attribute in the `include` and it's missing or empty, don't break because the type of the object can't be determined. If the request is for a collection and none of the elements has the attribute, it will not be added to the `linked` key, similar to what happens with simple includes.
1 parent 22202a1 commit 1d7d9fd

File tree

2 files changed

+31
-2
lines changed

2 files changed

+31
-2
lines changed

lib/active_model/serializer/adapter/json_api.rb

+2-2
Original file line numberDiff line numberDiff line change
@@ -68,8 +68,8 @@ def add_linked(resource_name, serializers, parent = nil)
6868

6969
resource_path = [parent, resource_name].compact.join('.')
7070

71-
if include_assoc?(resource_path)
72-
plural_name = serialized_object_type(serializers).pluralize.to_sym
71+
if include_assoc?(resource_path) && resource_type = serialized_object_type(serializers)
72+
plural_name = resource_type.pluralize.to_sym
7373
@top[:linked] ||= {}
7474
@top[:linked][plural_name] ||= []
7575

test/action_controller/json_api_linked_test.rb

+29
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,9 @@ def setup_post
2626
@first_comment.author = @author2
2727
@second_comment.post = @post
2828
@second_comment.author = nil
29+
@post2 = Post.new(id: 2, title: "Another Post", body: "Body")
30+
@post2.author = @author
31+
@post2.comments = []
2932
end
3033

3134
def render_resource_without_include
@@ -48,6 +51,18 @@ def render_resource_with_nested_has_many_include
4851
render json: @post, include: 'author,author.roles', adapter: :json_api
4952
end
5053

54+
def render_resource_with_missing_nested_has_many_include
55+
setup_post
56+
@post.author = @author2 # author2 has no roles.
57+
render json: @post, include: 'author,author.roles', adapter: :json_api
58+
end
59+
60+
def render_collection_with_missing_nested_has_many_include
61+
setup_post
62+
@post.author = @author2
63+
render json: [@post, @post2], include: 'author,author.roles', adapter: :json_api
64+
end
65+
5166
def render_collection_without_include
5267
setup_post
5368
render json: [@post], adapter: :json_api
@@ -124,6 +139,20 @@ def test_render_collection_with_include
124139
response = JSON.parse(@response.body)
125140
assert response.key? 'linked'
126141
end
142+
143+
def test_render_resource_with_nested_attributes_even_when_missing_associations
144+
get :render_resource_with_missing_nested_has_many_include
145+
response = JSON.parse(@response.body)
146+
assert response.key? 'linked'
147+
refute response['linked'].key? 'roles'
148+
end
149+
150+
def test_render_collection_with_missing_nested_has_many_include
151+
get :render_collection_with_missing_nested_has_many_include
152+
response = JSON.parse(@response.body)
153+
assert response.key? 'linked'
154+
assert response['linked'].key? 'roles'
155+
end
127156
end
128157
end
129158
end

0 commit comments

Comments
 (0)