Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 651
dev_054 Avatar asked Dec 02 '22 13:12

dev_054


1 Answers

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

like image 144
Narasimha Reddy - Geeker Avatar answered Jan 09 '23 13:01

Narasimha Reddy - Geeker