# As\_json and self-referential associations

**URL:** <https://www.ruby-forum.com/t/as-json-and-self-referential-associations/183574>\
**Category:** Rails\
**Created:** [February 16, 2010, 7:45pm UTC](https://www.ruby-forum.com/t/as-json-and-self-referential-associations/183574 "2010-02-16T19:45:19Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![reynar](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/r/e99b99/32.png) [@reynar](https://www.ruby-forum.com/u/reynar)\
**Post date:** [February 16, 2010, 7:45pm UTC](https://www.ruby-forum.com/t/as-json-and-self-referential-associations/183574/1 "2010-02-16T19:45:19Z")

</div>

Hi,

I’m using the new(?) as\_json methods within a rest api I am working  
on.

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

acts\_as\_tree

JSON\_ATTRS = [‘id’, ‘name’, ‘description’, ‘slug’]

def as\_json(options=nil)  
attributes.slice(\*JSON\_ATTRS).merge(:children =\>  
children, :ancestors =\> ancestors)  
end

end

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.
