【问题标题】:Active Model Serializers has_many associations活动模型序列化器 has_many 关联
【发布时间】:2017-02-03 03:36:57
【问题描述】:

我正在使用 gem active_model_serializers

序列化器:

class ProjectGroupSerializer < ActiveModel::Serializer
  attributes :id, :name, :description
  has_many :projects
end

class ProjectSerializer < ActiveModel::Serializer
  attributes :id, :name, :description
  belongs_to :project_group
end

控制器:

def index
  @project_groups = ProjectGroup.all.includes(:projects)
  render json: @project_groups, include: 'projects'
end

我收到以下回复

{
  "data": [
    {
      "id": "35",
      "type": "project_groups",
      "attributes": {
        "name": "sdsdf",
        "description": null
      },
      "relationships": {
        "projects": {
          "data": [
            {
              "id": "1",
              "type": "projects"
            },
            {
              "id": "2",
              "type": "projects"
            }
          ]
        }
      }
    }
  ],
  "included": [
    {
      "id": "1",
      "type": "projects",
      "attributes": {
        "name": "qweqwe",
        "description": null,
        "project_group_id": 1
      },
      "relationships": {
        "project_group": {
          "data": {
            "id": "1",
            "type": "project_groups"
          }
        }
      }
    },
    {
      "id": "2",
      "type": "projects",
      "attributes": {
        "name": "ewe",
        "description": null,
        "project_group_id": 2
      },
      "relationships": {
        "project_group": {
          "data": {
            "id": "2",
            "type": "project_groups"
          }
        }
      }
    }
  ]
}

我想检索 relationships object 内部的关联,而不是 外部(在 includedarray 中),如响应我收到的。有可能吗?

PS1:belongs_to 关联工作正常,关联位于 relationships object 中,就像在文档中一样。

PS2:我想这样做是因为我有 3 或 4 个关联,并且我想从每个对象访问它们。这样我得到回复的方式将是一团糟。

【问题讨论】:

  • 顺便说一句:这将是无效的 JSON:API,因此不太可能易于维护/支持。关系键应该包含resource identifier objects。如果您将它们保留为有效的 JSON:API,则 JSON:API 客户端应该为您解析它们(但我同意,如果编写自己的客户端,解析会有点麻烦)

标签: ruby-on-rails activemodel active-model-serializers


【解决方案1】:

您可以通过像这样手动定义项目来做到这一点。

class ProjectGroupSerializer < ActiveModel::Serializer
  attributes :id, :name, :description, :projects

  def projects
    object.projects.map do |project|
      ::ProjectSerializer.new(project).attributes
    end
  end

结束

【讨论】:

  • 感谢@NarashimaReddy,我还注意到如果我将配置更改为:json 格式,它也可以工作。
  • 对我来说效果很好。在JSONAPI 规范中看到的relationships 对象下的东西不是更好吗?
  • 我同意@mycellius,来自关联的记录必须在relationships 部分呈现。有人这样做吗?我正在尝试使其与 Grape + AMS 一起使用。
  • 我一直在寻找在关联上应用自定义序列化程序,但似乎没有任何效果。这是救命稻草。非常感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-07-14
  • 1970-01-01
  • 2016-07-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多