0

I am new in learning Ruby. In a program, I have used acts_as_tree to build an organization tree from a hierarchical table. Now, I wish to build a JSON string from the data contained in tree nodes. In the JSON output, each parent node will have an attribute called 'children' that will contain array of the records of the children of the parent node. To build such a JSON string, manually traversing the entire tree can be an option. But, what I wish to know is if there is any other way more elegant than this.

1
  • Please post any code you already tried. Commented May 8, 2015 at 21:21

2 Answers 2

1

I've done this on another project, but using a home grown tree structure. You'll need to override as_json on your object. I thought that doing something like:

def as_json(opts = {})
  super(opts.merge(include: :children))
end

would be sufficient, and it might be - maybe I have something else wrong with my codebase that prevents it from working. However, I was able to do it like this:

def as_json(opts = {})
  super(opts).merge(children: children.as_json)
end

This essentially creates a recursive as_json call since as_json will be called on all child elements, which will then have their as_json method called on their children and so forth.

Sign up to request clarification or add additional context in comments.

5 Comments

Should I define as_json inside the class creating ActiveRecord model?
Yeah, it's inside of the same model that has the acts_as_tree call.
Why are we overriding as_json, not to_json?
to_json returns a string, while as_json‘ returns a serializable hash that we can merge and manipulate. The latter also gets called when calling the former. The correct way to override default JSON serialization is via overriding as_json`.
The code you provided seems to work fine. Thanks. Can you please tell me if I want to recur as_json call upto a cetain depth, how can I achieve that?
0

Did you look at the JSON library?

try:

require 'json'
your_object.root.to_json

or even just:

require 'json'
your_object.to_json

You could probably create a Hash and Arrays from the root, or the object, and the children...

{root: your_object, children: your_object.children }.to_json

Since I never used the acts_as_tree library, I'm not sure if this would help.

2 Comments

I already did. But that gives the root node details, that's it.
Sounds like a great start. I updated the answer to see if extrapolating from what you already have can help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.