Skip to content

Commit 820db0b

Browse files
committed
Merge pull request #868 from groyoh/bug-with-nil-association
Fixed a bug that appears when a nil association is included
2 parents 48ed7cf + 6a0564a commit 820db0b

File tree

2 files changed

+28
-3
lines changed

2 files changed

+28
-3
lines changed

lib/active_model/serializer/adapter/json_api.rb

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -53,10 +53,11 @@ def add_link(resource, name, serializer)
5353
end
5454

5555
def add_included(resource_name, serializers, parent = nil)
56-
serializers = Array(serializers) unless serializers.respond_to?(:each)
57-
56+
unless serializers.respond_to?(:each)
57+
return unless serializers.object
58+
serializers = Array(serializers)
59+
end
5860
resource_path = [parent, resource_name].compact.join('.')
59-
6061
if include_assoc?(resource_path)
6162
@hash[:included] ||= []
6263

test/adapter/json_api/linked_test.rb

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ class Adapter
66
class JsonApi
77
class LinkedTest < Minitest::Test
88
def setup
9+
ActionController::Base.cache_store.clear
910
@author1 = Author.new(id: 1, name: 'Steve K.')
1011
@author2 = Author.new(id: 2, name: 'Tenderlove')
1112
@bio1 = Bio.new(id: 1, content: 'AMS Contributor')
@@ -225,6 +226,29 @@ def test_multiple_references_to_same_resource
225226

226227
assert_equal expected, adapter.serializable_hash[:included]
227228
end
229+
230+
def test_nil_link_with_specified_serializer
231+
@first_post.author = nil
232+
serializer = PostPreviewSerializer.new(@first_post)
233+
adapter = ActiveModel::Serializer::Adapter::JsonApi.new(
234+
serializer,
235+
include: ['author']
236+
)
237+
238+
expected = {
239+
data: {
240+
id: "10",
241+
title: "Hello!!",
242+
body: "Hello, world!!",
243+
type: "posts",
244+
links: {
245+
comments: { linkage: [ { type: "comments", id: '1' }, { type: "comments", id: '2' } ] },
246+
author: { linkage: nil }
247+
}
248+
}
249+
}
250+
assert_equal expected, adapter.serializable_hash
251+
end
228252
end
229253
end
230254
end

0 commit comments

Comments
 (0)