Skip to content

Commit

Permalink
Merge pull request rails-api#774 from nhocki/fix_nested_linked_objects
Browse files Browse the repository at this point in the history
Fix nested include attributes
  • Loading branch information
guilleiguaran committed Jan 13, 2015
2 parents 22202a1 + 1d7d9fd commit 6524938
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 2 deletions.
4 changes: 2 additions & 2 deletions lib/active_model/serializer/adapter/json_api.rb
Original file line number Diff line number Diff line change
Expand Up @@ -68,8 +68,8 @@ def add_linked(resource_name, serializers, parent = nil)

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] ||= []

Expand Down
29 changes: 29 additions & 0 deletions test/action_controller/json_api_linked_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,9 @@ def setup_post
@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
Expand All @@ -48,6 +51,18 @@ def render_resource_with_nested_has_many_include
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
Expand Down Expand Up @@ -124,6 +139,20 @@ def test_render_collection_with_include
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

0 comments on commit 6524938

Please sign in to comment.