如何获取fast_jsonapi返回关系的属性

时间:2019-04-21 10:49:51

标签: ruby-on-rails ruby fastjsonapi

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

我希望也能获得团队模型的属性。

3 个答案:

答案 0 :(得分:0)

fast_jsonapi实现json api specification,因此响应包括“ included”键,用于放置关系的序列化数据。这是默认行为

enter image description here

答案 1 :(得分:0)

如果使用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"

中找到关联的自定义数据

答案 2 :(得分: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