sherlock
sherlock

Reputation: 2807

Building a JSON string from act_as_tree tree

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.

Upvotes: 0

Views: 181

Answers (2)

Sean Hill
Sean Hill

Reputation: 15056

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.

Upvotes: 1

Myst
Myst

Reputation: 19221

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.

Upvotes: 0

Related Questions