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