ruby-on-rails-3 – 如何从祖先生成json树

前端之家收集整理的这篇文章主要介绍了ruby-on-rails-3 – 如何从祖先生成json树前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我用祖先制作一个目标树.我想使用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文件时,我得到了这个输出

{"#<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文件中呈现Goal-objects的内容

我试过这个:

@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

猜你在找的Ruby相关文章