From 5dcdfaaef35961b0ed4fc6f48317cc434d7933aa Mon Sep 17 00:00:00 2001 From: groyoh Date: Tue, 28 Apr 2015 22:20:21 +0200 Subject: [PATCH] Fixed a bug that appeared when json adapter serialize a nil association --- lib/active_model/serializer/adapter/json.rb | 2 +- test/adapter/json/belongs_to_test.rb | 7 +++++++ 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/lib/active_model/serializer/adapter/json.rb b/lib/active_model/serializer/adapter/json.rb index 8a78ffbb9..b36ef4007 100644 --- a/lib/active_model/serializer/adapter/json.rb +++ b/lib/active_model/serializer/adapter/json.rb @@ -23,7 +23,7 @@ def serializable_hash(options = {}) end end else - if association + if association && association.object @hash[name] = cache_check(association) do association.attributes(options) end diff --git a/test/adapter/json/belongs_to_test.rb b/test/adapter/json/belongs_to_test.rb index b711e20b4..1252fe388 100644 --- a/test/adapter/json/belongs_to_test.rb +++ b/test/adapter/json/belongs_to_test.rb @@ -34,6 +34,13 @@ def test_include_nil_author assert_equal({title: "Hello!!", body: "Hello, world!!", id: 43, comments: [], blog: {id: 999, name: "Custom blog"}, author: nil}, adapter.serializable_hash) end + + def test_include_nil_author_with_specified_serializer + serializer = PostPreviewSerializer.new(@anonymous_post) + adapter = ActiveModel::Serializer::Adapter::Json.new(serializer) + + assert_equal({title: "Hello!!", body: "Hello, world!!", id: 43, comments: [], author: nil}, adapter.serializable_hash) + end end end end