From 3bba334cf875cd3d9f53c4d1f9673558f71139d6 Mon Sep 17 00:00:00 2001 From: Guillermo Iguaran Date: Fri, 31 Oct 2014 14:30:59 -0500 Subject: [PATCH] JSON-API: Don't include linked section if associations are empty --- lib/active_model/serializer/adapter/json_api.rb | 8 +++----- test/adapter/json_api/has_many_test.rb | 10 ++++++++++ 2 files changed, 13 insertions(+), 5 deletions(-) diff --git a/lib/active_model/serializer/adapter/json_api.rb b/lib/active_model/serializer/adapter/json_api.rb index de0f3f83..596d54c0 100644 --- a/lib/active_model/serializer/adapter/json_api.rb +++ b/lib/active_model/serializer/adapter/json_api.rb @@ -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 diff --git a/test/adapter/json_api/has_many_test.rb b/test/adapter/json_api/has_many_test.rb index 2f74195f..6bcd43ca 100644 --- a/test/adapter/json_api/has_many_test.rb +++ b/test/adapter/json_api/has_many_test.rb @@ -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)