Skip to content

Commit 9aebc6c

Browse files
committed
Fix bugs with included resources
Make sure they're cached along with the including resource and remove duplicates
1 parent 5e560dd commit 9aebc6c

File tree

1 file changed

+11
-6
lines changed

1 file changed

+11
-6
lines changed

lib/active_model/serializer/adapter/json_api.rb

Lines changed: 11 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,7 @@ class JsonApi < Adapter
55
def initialize(serializer, options = {})
66
super
77
serializer.root = true
8-
@hash = {}
9-
@top = @options.fetch(:top) { @hash }
8+
@hash = { data: [] }
109

1110
if fields = options.delete(:fields)
1211
@fieldset = ActiveModel::Serializer::Fieldset.new(fields, serializer.json_key)
@@ -17,8 +16,14 @@ def initialize(serializer, options = {})
1716

1817
def serializable_hash(options = {})
1918
if serializer.respond_to?(:each)
20-
@hash[:data] = serializer.map do |s|
21-
self.class.new(s, @options.merge(top: @top, fieldset: @fieldset)).serializable_hash[:data]
19+
serializer.each do |s|
20+
result = self.class.new(s, @options.merge(fieldset: @fieldset)).serializable_hash
21+
@hash[:data] << result[:data]
22+
23+
if result[:included]
24+
@hash[:included] ||= []
25+
@hash[:included] |= result[:included]
26+
end
2227
end
2328
else
2429
@hash = cached_object do
@@ -53,14 +58,14 @@ def add_included(resource_name, serializers, parent = nil)
5358
resource_path = [parent, resource_name].compact.join('.')
5459

5560
if include_assoc?(resource_path)
56-
@top[:included] ||= []
61+
@hash[:included] ||= []
5762

5863
serializers.each do |serializer|
5964
attrs = attributes_for_serializer(serializer, @options)
6065

6166
add_resource_links(attrs, serializer, add_included: false)
6267

63-
@top[:included].push(attrs) unless @top[:included].include?(attrs)
68+
@hash[:included].push(attrs) unless @hash[:included].include?(attrs)
6469
end
6570
end
6671

0 commit comments

Comments
 (0)