9

我使用祖先来制作目标树。我想使用 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 文件中呈现目标对象的内容?

我试过这个:

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

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

4

3 回答 3

11

我在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
于 2012-03-31T14:19:40.010 回答
2

受此启发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
于 2013-04-18T11:07:51.087 回答
1

前几天我遇到了这个问题(祖先 2.0.0)。我根据我的需要修改了约翰的答案。我有三个使用祖先的模型,因此扩展 OrderedHash 以添加 as_json 方法而不是将 json_tree 添加到三个模型是有意义的。

由于这个线程非常有帮助,我想我会分享这个修改。

将此设置为 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

我们调用模型并使用它的默认 json 行为。不确定我应该调用_json还是作为_json。我在这里使用了 as_json ,它在我的代码中工作。

在控制器中

...
format.json { render :json => @goal.arrange}
...
于 2014-01-31T02:51:15.427 回答