As_json and self-referential associations


I’m using the new(?) as_json methods within a rest api I am working

However I am not sure how you are supposed to, or whether it is
designed to handle multiple variations of association inclusion.

For example I have a model using acts_as_tree, so that each instance
has children and a parent:

class CatalogueCategory < ActiveRecord::Base


JSON_ATTRS = [‘id’, ‘name’, ‘description’, ‘slug’]

def as_json(options=nil)
attributes.slice(*JSON_ATTRS).merge(:children =>
children, :ancestors => ancestors)


The ancestors reference is an array of parent, grand parent etc
categories back up to the root node.

However when I call .as_json on my category of interest it tries to
include the children of each ancestor category which each have
ancestors… and we end up in an infinite loop.

Ideally I would like to be able to specify different treatment of the
same model depending on some context. That is I would like to be able
to specify that ancestor categories do not include :children
or :ancestors in their attributes for the as_json call.

I think most of this as_json functionality is part of 2-3.stable post
2.3.5 but hoped someone might have some guidance.

Thanks, Andrew.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs