diff --git a/lib/active_model/serializer/adapter/json_api.rb b/lib/active_model/serializer/adapter/json_api.rb index a7ca89a7..dd84e633 100644 --- a/lib/active_model/serializer/adapter/json_api.rb +++ b/lib/active_model/serializer/adapter/json_api.rb @@ -68,8 +68,8 @@ module ActiveModel resource_path = [parent, resource_name].compact.join('.') - if include_assoc?(resource_path) - plural_name = serialized_object_type(serializers).pluralize.to_sym + if include_assoc?(resource_path) && resource_type = serialized_object_type(serializers) + plural_name = resource_type.pluralize.to_sym @top[:linked] ||= {} @top[:linked][plural_name] ||= [] diff --git a/test/action_controller/json_api_linked_test.rb b/test/action_controller/json_api_linked_test.rb index dca55e67..71b69b0e 100644 --- a/test/action_controller/json_api_linked_test.rb +++ b/test/action_controller/json_api_linked_test.rb @@ -26,6 +26,9 @@ module ActionController @first_comment.author = @author2 @second_comment.post = @post @second_comment.author = nil + @post2 = Post.new(id: 2, title: "Another Post", body: "Body") + @post2.author = @author + @post2.comments = [] end def render_resource_without_include @@ -48,6 +51,18 @@ module ActionController render json: @post, include: 'author,author.roles', adapter: :json_api end + def render_resource_with_missing_nested_has_many_include + setup_post + @post.author = @author2 # author2 has no roles. + render json: @post, include: 'author,author.roles', adapter: :json_api + end + + def render_collection_with_missing_nested_has_many_include + setup_post + @post.author = @author2 + render json: [@post, @post2], include: 'author,author.roles', adapter: :json_api + end + def render_collection_without_include setup_post render json: [@post], adapter: :json_api @@ -124,6 +139,20 @@ module ActionController response = JSON.parse(@response.body) assert response.key? 'linked' end + + def test_render_resource_with_nested_attributes_even_when_missing_associations + get :render_resource_with_missing_nested_has_many_include + response = JSON.parse(@response.body) + assert response.key? 'linked' + refute response['linked'].key? 'roles' + end + + def test_render_collection_with_missing_nested_has_many_include + get :render_collection_with_missing_nested_has_many_include + response = JSON.parse(@response.body) + assert response.key? 'linked' + assert response['linked'].key? 'roles' + end end end end