merge multiple nested associations

This commit is contained in:
Jan Wendt
2016-03-18 09:20:11 +01:00
parent a105c603c4
commit a30f53de76
7 changed files with 145 additions and 24 deletions

38
test/fixtures/poro.rb vendored
View File

@@ -53,6 +53,26 @@ class SpecialPost < Post
end
end
class Type < Model
end
class SelfReferencingUser < Model
def type
@type ||= Type.new(name: 'N1')
end
def parent
@parent ||= SelfReferencingUserParent.new(name: 'N1')
end
end
class SelfReferencingUserParent < Model
def type
@type ||= Type.new(name: 'N2')
end
def parent
end
end
class Comment < Model
end
@@ -87,6 +107,22 @@ class UserSerializer < ActiveModel::Serializer
has_one :profile
end
class TypeSerializer < ActiveModel::Serializer
attributes :name
end
class SelfReferencingUserParentSerializer < ActiveModel::Serializer
attributes :name
has_one :type, serializer: TypeSerializer, embed: :ids, include: true
end
class SelfReferencingUserSerializer < ActiveModel::Serializer
attributes :name
has_one :type, serializer: TypeSerializer, embed: :ids, include: true
has_one :parent, serializer: SelfReferencingUserSerializer, embed: :ids, include: true
end
class UserInfoSerializer < ActiveModel::Serializer
has_one :user, serializer: UserSerializer
end
@@ -176,7 +212,7 @@ end
class NameKeyPostSerializer < ActiveModel::Serializer
attributes :title, :body
has_many :comments
end

View File

@@ -14,6 +14,36 @@ module ActiveModel
assert_equal([:comments],
another_inherited_serializer_klass._associations.keys)
end
def test_multiple_nested_associations
parent = SelfReferencingUserParent.new(name: "The Parent")
child = SelfReferencingUser.new(name: "The child", parent: parent)
self_referencing_user_serializer = SelfReferencingUserSerializer.new(child)
result = self_referencing_user_serializer.as_json
expected_result = {
"self_referencing_user"=>{
:name=>"The child",
"type_id"=>child.type.object_id,
"parent_id"=>child.parent.object_id
},
"types"=>[
{
:name=>"N1",
},
{
:name=>"N2",
}
],
"parents"=>[
{
:name=>"N1",
"type_id"=>child.parent.type.object_id,
"parent_id"=>nil
}
]
}
assert_equal(expected_result, result)
end
end
end
end