Active Model Serializers has_many association

dev*_*054 1 ruby-on-rails activemodel active-model-serializers

我正在使用宝石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
Run Code Online (Sandbox Code Playgroud)

控制器:

def index
  @project_groups = ProjectGroup.all.includes(:projects)
  render json: @project_groups, include: 'projects'
end
Run Code Online (Sandbox Code Playgroud)

我收到以下回复:

{
  "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"
          }
        }
      }
    }
  ]
}
Run Code Online (Sandbox Code Playgroud)

我想检索关系 对象内的关联,而不是included array我收到的响应中的外部(in ).可能吗?

PS1:belongs_to关联工作正常,关联来自关系 对象,如在docs中.

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

Nar*_*ker 10

您可以通过手动定义项目来完成此操作.

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

  def projects
    object.projects.map do |project|
      ::ProjectSerializer.new(project).attributes
    end
  end
Run Code Online (Sandbox Code Playgroud)

结束

  • 谢谢@NarashimaReddy,我还注意到如果我将配置更改为格式 `:json`,它也可以工作。 (2认同)