Skip to content

Commit

Permalink
Merge pull request rails-api#710 from ride/fix-empty-linked
Browse files Browse the repository at this point in the history
JSON-API: Don't include linked section if associations are empty
  • Loading branch information
kurko committed Nov 2, 2014
2 parents deaf55e + 3bba334 commit 80ece39
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 5 deletions.
8 changes: 3 additions & 5 deletions lib/active_model/serializer/adapter/json_api.rb
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,6 @@ def serializable_hash(options = {})

serializer.each_association do |name, association, opts|
@hash[@root][:links] ||= {}
unless opts[:embed] == :ids
@hash[:linked] ||= {}
end

if association.respond_to?(:each)
add_links(name, association, opts)
Expand All @@ -47,7 +44,8 @@ def add_links(name, serializers, options)
@hash[@root][:links][name][:ids] += serializers.map{|serializer| serializer.id.to_s }
end

unless options[:embed] == :ids
unless options[:embed] == :ids || serializers.count == 0
@hash[:linked] ||= {}
@hash[:linked][name] ||= []
@hash[:linked][name] += serializers.map { |item| attributes_for_serializer(item, options) }
end
Expand All @@ -66,7 +64,7 @@ def add_link(name, serializer, options)

unless options[:embed] == :ids
plural_name = name.to_s.pluralize.to_sym

@hash[:linked] ||= {}
@hash[:linked][plural_name] ||= []
@hash[:linked][plural_name].push attributes_for_serializer(serializer, options)
end
Expand Down
10 changes: 10 additions & 0 deletions test/adapter/json_api/has_many_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,15 @@ class HasManyTest < Minitest::Test
def setup
@author = Author.new(id: 1, name: 'Steve K.')
@post = Post.new(id: 1, title: 'New Post', body: 'Body')
@post_without_comments = Post.new(id: 2, title: 'Second Post', body: 'Second')
@first_comment = Comment.new(id: 1, body: 'ZOMG A COMMENT')
@second_comment = Comment.new(id: 2, body: 'ZOMG ANOTHER COMMENT')
@post.comments = [@first_comment, @second_comment]
@post_without_comments.comments = []
@first_comment.post = @post
@second_comment.post = @post
@post.author = @author
@post_without_comments.author = nil
@blog = Blog.new(id: 1, name: "My Blog!!")
@blog.writer = @author
@blog.articles = [@post]
Expand All @@ -33,6 +36,13 @@ def test_includes_linked_comments
], @adapter.serializable_hash[:linked][:comments])
end

def test_no_include_linked_if_comments_is_empty
serializer = PostSerializer.new(@post_without_comments)
adapter = ActiveModel::Serializer::Adapter::JsonApi.new(serializer)

assert_nil adapter.serializable_hash[:linked]
end

def test_include_type_for_association_when_is_different_than_name
serializer = BlogSerializer.new(@blog)
adapter = ActiveModel::Serializer::Adapter::JsonApi.new(serializer)
Expand Down

0 comments on commit 80ece39

Please sign in to comment.