7

我有一个 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"
    }
  }
}

而我也期望获得我的团队模型的属性。

4

3 回答 3

4

fast_jsonapi 实现json api 规范,因此响应包括“包含”键,其中放置关系的序列化数据。这是默认行为

在此处输入图像描述

于 2019-04-21T11:22:59.243 回答
1

如果您使用 ,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-01-23T06:45:07.283 回答
0

如果您像这样使用,那么也许可以解决您的问题

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

于 2020-05-08T08:00:41.930 回答