From 6a0564a241baf3da414874ada567be2cef99cae5 Mon Sep 17 00:00:00 2001 From: Yohan Robert Date: Fri, 3 Apr 2015 12:50:05 +0200 Subject: [PATCH] Fixed a bug that appears when a nil association is included --- .../serializer/adapter/json_api.rb | 7 +++--- test/adapter/json_api/linked_test.rb | 24 +++++++++++++++++++ 2 files changed, 28 insertions(+), 3 deletions(-) diff --git a/lib/active_model/serializer/adapter/json_api.rb b/lib/active_model/serializer/adapter/json_api.rb index 0f0ad59ae..027ce7887 100644 --- a/lib/active_model/serializer/adapter/json_api.rb +++ b/lib/active_model/serializer/adapter/json_api.rb @@ -53,10 +53,11 @@ def add_link(resource, name, serializer) end def add_included(resource_name, serializers, parent = nil) - serializers = Array(serializers) unless serializers.respond_to?(:each) - + unless serializers.respond_to?(:each) + return unless serializers.object + serializers = Array(serializers) + end resource_path = [parent, resource_name].compact.join('.') - if include_assoc?(resource_path) @hash[:included] ||= [] diff --git a/test/adapter/json_api/linked_test.rb b/test/adapter/json_api/linked_test.rb index be228c470..6ea6fed9e 100644 --- a/test/adapter/json_api/linked_test.rb +++ b/test/adapter/json_api/linked_test.rb @@ -6,6 +6,7 @@ class Adapter class JsonApi class LinkedTest < Minitest::Test def setup + ActionController::Base.cache_store.clear @author1 = Author.new(id: 1, name: 'Steve K.') @author2 = Author.new(id: 2, name: 'Tenderlove') @bio1 = Bio.new(id: 1, content: 'AMS Contributor') @@ -225,6 +226,29 @@ def test_multiple_references_to_same_resource assert_equal expected, adapter.serializable_hash[:included] end + + def test_nil_link_with_specified_serializer + @first_post.author = nil + serializer = PostPreviewSerializer.new(@first_post) + adapter = ActiveModel::Serializer::Adapter::JsonApi.new( + serializer, + include: ['author'] + ) + + expected = { + data: { + id: "10", + title: "Hello!!", + body: "Hello, world!!", + type: "posts", + links: { + comments: { linkage: [ { type: "comments", id: '1' }, { type: "comments", id: '2' } ] }, + author: { linkage: nil } + } + } + } + assert_equal expected, adapter.serializable_hash + end end end end