- Notifications
You must be signed in to change notification settings - Fork 1.4k
Description
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 endLet'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 endPerhaps 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.