How to generate json tree from ancestry

↘锁芯ラ 提交于 2019-12-01 03:28:27
Johan Hovda

I got some help from user tejo at https://github.com/stefankroes/ancestry/issues/82.

The solution is to put this method in the goal model:

def self.json_tree(nodes)
    nodes.map do |node, sub_nodes|
      {:name => node.name, :id => node.id, :children => Goal.json_tree(sub_nodes).compact}
    end
end

and then make the controller look like this:

@goals = Goal.arrange
respond_to do |format|
  format.html # index.html.erb
  format.xml  { render :xml => @goals }
  format.json { render :json =>  Goal.json_tree(@goals)}
end

Inspired from this https://github.com/stefankroes/ancestry/wiki/arrange_as_array

def self.arrange_as_json(options={}, hash=nil)
  hash ||= arrange(options)
  arr = []
  hash.each do |node, children|
    branch = {id: node.id, name: node.name}
    branch[:children] = arrange_as_json(options, children) unless children.empty?
    arr << branch
  end
  arr
end
user2939617

I ran into this problem the other day (ancestry 2.0.0). I modified Johan's answer for my needs. I have three models using ancestry, so it made sense to extend OrderedHash to add a as_json method instead of adding json_tree to three models.

Since this thread was so helpful, I thought I'd share this modification.

Set this up as a module or monkey patch for ActiveSupport::OrderedHash

def as_json(options = {})
    self.map do |k,v|
        x = k.as_json(options)
        x["children"] = v.as_json(options)
        x
    end
end

We call the model and use it's default json behavior. Not sure If I should call to_json or as_json. I've used as_json here and it works in my code.

In the controller

...
format.json { render :json => @goal.arrange}
...
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!