简体   繁体   中英

Active Model Serializers has_many associations

I'm using the gem active_model_serializers .

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

Controller:

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

I'm getting the following response :

{
  "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"
          }
        }
      }
    }
  ]
}

I want to retrieve the associations inside the relationships object , not outside (in included array ) as in the response that I'm receiving. Is it possible?

PS1: belongs_to associations works fine, the associations comes inside the relationships object , as in docs.

PS2: I want to do this because I have 3 or 4 associations and I want to access them from each object. This way that I'm getting the response will be a real mess.

You can do this by defining projects manually like this.

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

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

end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM