Active Model Serializers has_many association

时间:2017-02-03 03:36:57

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

我正在使用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"
          }
        }
      }
    }
  ]
}

我想检索关系 对象中的关联,而不是 之外的关联(在included array中)就像我收到的回复一样。有可能吗?

PS1: belongs_to 关联正常,关联来自关系 对象,就像在文档中一样。

PS2:我想这样做,因为我有3个或4个关联,我想从每个对象访问它们。这样我得到的回复将是一个真正的混乱。

1 个答案:

答案 0 :(得分:10)

您可以通过手动定义项目来实现此目的。

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

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