Skip to content

Limiting stack depth association embeds #540

@bradynpoulsen

Description

@bradynpoulsen

I have been unable to find a way to limit embedding associations when they refer each other.

Example

Lets say I have a Project and a Client where the client has_many :projects.

app/serializers/project_serializer.rb

class ProjectSerializer < ActiveModel::Serializer
  embed :ids, include: true

  attributes :id, :name
  has_one :client
end

app/serializers/client_serializer.rb

class ClientSerializer < ActiveModel::Serializer
  embed :ids, include: true

  attributes :id, :name
  has_many :projects
end

But because it continues to include all of the clients and projects until all of the embeds have been processed.

So if I request /projects/3.json, I might get the result:

{
  "clients": [
    {"id": 1, "name": "HelloWorld, Inc", "project_ids":[1,3]}
  ],
  "projects": [
    {"id": 1, "name": "My First Project", "client_id": 1},
    {"id": 3, "name": "My Cool Idea", "client_id": 1}
  ],
  "project": {"id": 3, "name": "My Cool Idea", "client_id": 1}
}

when all I really wanted was just the clients and project entries because of redundant data transfer.

Possible Solution

Of course there are ways to fix my purpose, but I wish there were some function we could define to define the scope of embeds, ie:

class ProjectSerializer < ActiveModel::Serializer
  def embed_level(level)
    embed :ids, include: true if level < 2
  end
end

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions