Fix issue with embedding multiple associations under the same root key

This commit is contained in:
Anthony Dmitriyev 2015-03-13 13:55:38 +00:00
parent 55210ab61f
commit d62463de15
3 changed files with 24 additions and 1 deletions

View File

@ -204,7 +204,9 @@ end
association_serializer = build_serializer(association)
# we must do this always because even if the current association is not
# embeded in root, it might have its own associations that are embeded in root
hash.merge!(association_serializer.embedded_in_root_associations) {|key, oldval, newval| [newval, oldval].flatten }
hash.merge!(association_serializer.embedded_in_root_associations) do |key, oldval, newval|
oldval.merge(newval) { |_, oldval, newval| [oldval, newval].flatten.uniq }
end
if association.embed_in_root?
if association.embed_in_root_key?

View File

@ -74,6 +74,10 @@ class ARSectionSerializer < ActiveModel::Serializer
attributes 'name'
end
class AREmbeddedSerializer < ActiveModel::Serializer
has_many :ar_tags, :ar_comments
end
ARPost.create(title: 'New post',
body: 'A body!!!',
ar_section: ARSection.create(name: 'ruby')).tap do |post|

View File

@ -58,6 +58,22 @@ module ActiveModel
end
end
def test_serialization_embedding_ids_in_common_root_key
post_serializer = AREmbeddedSerializer.new(@post)
embed(AREmbeddedSerializer, embed: :ids, embed_in_root: true, embed_in_root_key: :linked) do
embed(ARCommentSerializer, embed: :ids, embed_in_root: true, embed_in_root_key: :linked) do
assert_equal({
'ar_tags' => [{ name: 'short' },
{ name: 'whiny' },
{ name: 'happy' }],
'ar_comments' => [{ body: 'what a dumb post', 'ar_tag_ids' => [3, 2] },
{ body: 'i liked it', 'ar_tag_ids' => [3, 1] }]
}, post_serializer.as_json[:linked])
end
end
end
private
def embed(serializer_class, options = {})
@ -66,6 +82,7 @@ module ActiveModel
serializer_class._associations.each_value do |association|
association.embed = options[:embed]
association.embed_in_root = options[:embed_in_root]
association.embed_in_root_key = options[:embed_in_root_key]
end
yield