我有以下模式:
class Team < ApplicationRecord
# Associations
has_many :users
has_and_belongs_to_many :projects
belongs_to :team_leader, class_name: 'User'
end我使用的是active_model_serializers版本0.10.6
下面是我的序列化程序中的代码:
class TeamSerializer < ActiveModel::Serializer
attributes :id, :name, :can_delete, :can_edit
has_many :projects
has_many :users
belongs_to :team_leader
end以下是序列化的结果:
{
"data":[
{
"id":"1",
"type":"teams",
"attributes":{
"name":"OA",
"can-delete":true,
"can-edit":true
},
"relationships":{
"projects":{
"data":[
{
"id":"2",
"type":"projects"
}
]
},
"users":{
"data":[
{
"id":"25",
"type":"users"
}
]
},
"team-leader":{
"data":{
"id":"25",
"type":"team-leaders"
}
}
}
}
]
}我遇到的问题是"team_leader“关系,正如我所预期的那样,它是”用户“类型,但事实并非如此。它是类型为的团队领导者,但我没有模范的团队领导,这在我的前端应用程序(这是一个成员2.14应用程序)中造成了混乱。是否有一种仅针对关系和序列化程序重写类型的方法?如果没有,我愿意听取任何解决这个问题的建议.
发布于 2017-08-31 03:05:24
试试这个:
class TeamSerializer < ActiveModel::Serializer
attributes :id, :name, :can_delete, :can_edit
has_many :projects
has_many :users
attribute :team_leader do
team_leader = object.team_leader
UserSerializer.new(team_leader) if team_leader
end
end这当然意味着存在UserSerializer,但它可能非常简单,例如:
class UserSerializer < ActiveModel::Serializer
attributes :id, :foo, :bar, :etc
endhttps://stackoverflow.com/questions/45966094
复制相似问题