我有一个包含许多模型的rails api,这些模型正在被fast_jsonapi gem序列化。
这是我的模型的样子:
class Shift < ApplicationRecord
belongs_to :team, optional: true
...class Team < ApplicationRecord
has_many :shifts
...这是序列化程序的样子。
class ShiftSerializer
include FastJsonapi::ObjectSerializer
...
belongs_to :team
...
end序列化可以正常工作。然而,尽管我包含了复合团队文档:
def index
shifts = policy_scope(Shift).includes(:team)
options = {}
options[:include] = [:team, :'team.name', :'team.color']
render json: ShiftSerializer.new(shifts, options)
end我仍然将对象设置为这样的格式:
...
relationships: {
team: {
data: {
id: "22",
type: "Team"
}
}
}而我希望也能得到我的团队模型的属性。
发布于 2019-04-21 19:22:59
发布于 2020-01-23 14:45:07
如果使用options[:include],则应该为包含的模型创建序列化程序,并自定义响应中包含的内容。
在您的情况下,如果您使用
ShiftSerializer.new(shifts, include: [:team]).serializable_hash您应该创建一个新的序列化程序serializers/team_serializer.rb
class TeamSerializer
include FastJsonapi::ObjectSerializer
attributes :name, :color
end这样,您的响应将是
{
data: [
{
id: 1,
type: "shift",
relationships: {
team: {
data: {
id: "22",
type: "Team"
}
}
}
}
],
included: [
id: 22,
type: "Team",
attributes: {
name: "example",
color: "red"
}
]
}您将在响应"included"中找到您的关联的自定义数据
发布于 2020-05-08 16:00:42
如果你这样使用,也许你的问题就解决了。
class Shift < ApplicationRecord
belongs_to :team, optional:true
accepts_nested_attributes_for :team
end 在您的ShiftSerializer.rb中的
请编写此代码,
attribute :team do |object|
object.team.as_json
end,您将获得所需的自定义数据。
参考:https://github.com/Netflix/fast_jsonapi/issues/160#issuecomment-379727174
https://stackoverflow.com/questions/55782066
复制相似问题