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.
2 Answers
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.
5 Comments
as_json inside the class creating ActiveRecord model?acts_as_tree call.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`.as_json call upto a cetain depth, how can I achieve that?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.