Skip to content

Commit d62463d

Browse files
committed
Fix issue with embedding multiple associations under the same root key
1 parent 55210ab commit d62463d

File tree

3 files changed

+24
-1
lines changed

3 files changed

+24
-1
lines changed

lib/active_model/serializer.rb

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -204,7 +204,9 @@ def embedded_in_root_associations
204204
association_serializer = build_serializer(association)
205205
# we must do this always because even if the current association is not
206206
# embeded in root, it might have its own associations that are embeded in root
207-
hash.merge!(association_serializer.embedded_in_root_associations) {|key, oldval, newval| [newval, oldval].flatten }
207+
hash.merge!(association_serializer.embedded_in_root_associations) do |key, oldval, newval|
208+
oldval.merge(newval) { |_, oldval, newval| [oldval, newval].flatten.uniq }
209+
end
208210

209211
if association.embed_in_root?
210212
if association.embed_in_root_key?

test/fixtures/active_record.rb

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -74,6 +74,10 @@ class ARSectionSerializer < ActiveModel::Serializer
7474
attributes 'name'
7575
end
7676

77+
class AREmbeddedSerializer < ActiveModel::Serializer
78+
has_many :ar_tags, :ar_comments
79+
end
80+
7781
ARPost.create(title: 'New post',
7882
body: 'A body!!!',
7983
ar_section: ARSection.create(name: 'ruby')).tap do |post|

test/integration/active_record/active_record_test.rb

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,22 @@ def test_serialization_embedding_ids_including_in_root
5858
end
5959
end
6060

61+
def test_serialization_embedding_ids_in_common_root_key
62+
post_serializer = AREmbeddedSerializer.new(@post)
63+
64+
embed(AREmbeddedSerializer, embed: :ids, embed_in_root: true, embed_in_root_key: :linked) do
65+
embed(ARCommentSerializer, embed: :ids, embed_in_root: true, embed_in_root_key: :linked) do
66+
assert_equal({
67+
'ar_tags' => [{ name: 'short' },
68+
{ name: 'whiny' },
69+
{ name: 'happy' }],
70+
'ar_comments' => [{ body: 'what a dumb post', 'ar_tag_ids' => [3, 2] },
71+
{ body: 'i liked it', 'ar_tag_ids' => [3, 1] }]
72+
}, post_serializer.as_json[:linked])
73+
end
74+
end
75+
end
76+
6177
private
6278

6379
def embed(serializer_class, options = {})
@@ -66,6 +82,7 @@ def embed(serializer_class, options = {})
6682
serializer_class._associations.each_value do |association|
6783
association.embed = options[:embed]
6884
association.embed_in_root = options[:embed_in_root]
85+
association.embed_in_root_key = options[:embed_in_root_key]
6986
end
7087

7188
yield

0 commit comments

Comments
 (0)