【问题标题】:How to generate json tree from ancestry如何从祖先生成json树
【发布时间】:2012-03-30 13:32:45
【问题描述】:

我使用祖先来制作目标树。我想使用 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 个空格,或用反引号 [`] 包围),您不必随机删除 &lt;&gt;s。 stackoverflow.com/editing-help

标签: ruby-on-rails-3 json ancestry


【解决方案1】:

我从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

【讨论】:

  • 看来你不需要祖先了
  • 我是唯一一个在日志中收到消息的人吗? N+1 Query detected Directory =&gt; [:children] Add to your finder: :includes =&gt; [:children] N+1 Query method call stack我正在使用closure_tree
【解决方案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

【讨论】:

    【解决方案3】:

    前几天我遇到了这个问题(祖先 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 行为。不确定我应该调用 to_json 还是 as_json。我在这里使用了 as_json,它可以在我的代码中使用。

    在控制器中

    ...
    format.json { render :json => @goal.arrange}
    ...
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-24
      • 1970-01-01
      • 2016-09-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多