我用祖先制作一个目标树.我想使用json将该树的内容发送到浏览器.
我的控制器是这样的:
@goals = Goal.arrange respond_to do |format| format.html # index.html.erb format.xml { render :xml => @goals } format.json { render :json => @goals} end
{"#<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>":{}}}
我试过这个:
@goals.map! {|goal| {:id => goal.id.to_s}
但它不起作用,因为@goals是一个有序的哈希.
解决方法
我在
https://github.com/stefankroes/ancestry/issues/82用户tejo得到了一些帮助.
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
然后使控制器看起来像这样:
@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