Skip to content

Infinite loop in circular associations #211

@heartsentwined

Description

@heartsentwined

active_model_serializers can handle self-referencing associations fine, e.g. categories, but it will run into an infinite loop if you try to sideload circular associations. An example is the twitter-esque follower-followed association pair.

class BaseSerializer < ActiveModel::Serializer
  embed :ids, include: true
end

class FollowerSerializer < BaseSerializer
  has_many :followeds
end

class FollowedSerializer < BaseSerializer
  has_many :followers
end

Let's say you start by requesting a follower. active_model_serializers will traverse its followeds, sideload the followed models by initiating a new FollowedSerializer for each, and if any followed points back to the original follower via its own has_many :followers association, we have an infinite loop.

The current workaround is, unfortunately, disable sideloading entirely for the offending associations.

class BaseSerializer < ActiveModel::Serializer
  embed :ids, include: true
end

class FollowerSerializer < BaseSerializer
  has_many :followeds, embed: :ids, include: false
end

class FollowedSerializer < BaseSerializer
  has_many :followers, embed: :ids, include: false
end

Perhaps keeping track of the model + primary key while loading associations (recursively) can solve this issue? This way the same model will only be serialized once.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions