【问题标题】:How to get the fast_jsonapi to return the attributes of the relationships如何让 fast_jsonapi 返回关系的属性
【发布时间】:2019-09-10 22:02:24
【问题描述】:

我有一个带有多个模型的 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"
    }
  }
}

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

【问题讨论】:

    标签: ruby-on-rails ruby fastjsonapi


    【解决方案1】:

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

    【讨论】:

    • 默认行为确实只显示 id 和 type,但是,根据他们的文档,通过使用带有 include 属性的选项哈希,我应该得到团队名称和团队颜色。文档链接:github.com/Netflix/fast_jsonapi#compound-document
    • 我附上了截图来可视化它
    • 您也应该以其他方式使用options[:include] = [:team, :'team.name', :'team.color']options = { include: [:team], fields: { team: [:name, :color] } } 或创建单独的 TeamSerializer 并使用它:options = { include: [:team] } 并在 ShiftSerializer 中:belongs_to :team, serializer: TeamSerializer
    • 我按照文档所说的(字面意思是复制粘贴),但它不起作用。将尝试您提到的另一种方式。我已经创建了一个用于团队端点的团队序列化程序。将及时向大家发布。干杯!
    • 也尝试了第二种方法,但我仍然得到相同的结果。我觉得这很奇怪,因为我实际上是从他们拥有的文档中获取代码
    【解决方案2】:

    如果您使用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"中找到您关联的自定义数据

    【讨论】:

      【解决方案3】:

      如果你这样使用,也许可以解决你的问题

      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

      【讨论】:

        猜你喜欢
        • 2019-06-04
        • 2022-01-22
        • 2021-04-16
        • 1970-01-01
        • 1970-01-01
        • 2016-07-21
        • 1970-01-01
        • 2020-06-16
        • 2016-09-06
        相关资源
        最近更新 更多