mirror of
https://github.com/ditkrg/active_model_serializers.git
synced 2026-01-23 06:16:50 +00:00
JSON-API: Don't include linked section if associations are empty
This commit is contained in:
parent
5acd0be287
commit
3bba334cf8
@ -18,9 +18,6 @@ module ActiveModel
|
||||
|
||||
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)
|
||||
@ -47,7 +44,8 @@ module ActiveModel
|
||||
@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
|
||||
@ -66,7 +64,7 @@ module ActiveModel
|
||||
|
||||
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
|
||||
|
||||
@ -8,12 +8,15 @@ module ActiveModel
|
||||
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]
|
||||
@ -33,6 +36,13 @@ module ActiveModel
|
||||
], @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)
|
||||
|
||||
Loading…
Reference in New Issue
Block a user