如何从祖先生成json树 [英] How to generate json tree from ancestry

查看:128
本文介绍了如何从祖先生成json树的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用祖先树成目标树.我想使用json将那棵树的内容发送到浏览器.

I use ancestry to make a tree of goals. I would like to send the contents of that tree to the browser using json.

我的控制器是这样的:

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

当我打开json文件时,得到以下输出:

When I open the json file, I get this output:

{"#<Goal:0x7f8664332088>":{"#<Goal:0x7f86643313b8>":{"#<Goal:0x7f8664331048>":{"#<Goal:0x7f8664330c10>":{}},"#<Goal:0x7f8664330e68>":{}},"#<Goal:0x7f86643311b0>":{}},"#<Goal:0x7f8664331f70>":{},"#<Goal:0x7f8664331d18>":{},"#<Goal:0x7f8664331bd8>":{},"#<Goal:0x7f8664331a20>":{},"#<Goal:0x7f86643318e0>":{},"#<Goal:0x7f8664331750>":{},"#<Goal:0x7f8664331548>":{"#<Goal:0x7f8664330aa8>":{}}}

如何在json文件中呈现目标对象的内容?

How can I render the contents of the Goal-objects in the json file?

我已经尝试过了:

@goals.map! {|goal| {:id => goal.id.to_s}

但是它不起作用,因为@goals是有序哈希.

but it doesn't work, since @goals is an ordered hash.

推荐答案

我在解决方案是将此方法放入目标模型:

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

这篇关于如何从祖先生成json树的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆