【问题标题】:acts_as_tree and to_json or from_jsonact_as_tree 和 to_json 或 from_json
【发布时间】:2011-08-26 16:51:53
【问题描述】:

您好:有没有人可以将acts_as_tree 模型转换为包含其所有节点的json 的解决方案?我使用 :include=>:children 进行了验证,但这只会下降到一个级别。知道如何迭代整个树吗?

【问题讨论】:

    标签: ruby-on-rails


    【解决方案1】:

    使用递归的帮助程序(或私有方法)并将嵌套模型转换为嵌套哈希,然后使用to_json 生成 json 字符串。

    我需要在 HTML/Erb 视图中生成 Json,但如果您需要从控制器操作生成 Json,或者使用 Erb 模板生成 Json,则应该适用相同的想法。我还需要一个(硬编码的)根节点,如果不需要,你可以跳过它。

    categories.html.erb

    <script type="text/javascript">
      $(function(){
          var json = {
            id: "node00",
            name: "New Pathway",
            data: {},
            children: 
    <%= @categories.select { |c| c.root? && !c.leaf? }.collect { |c| category_to_spacetree_json(c) }.to_json.html_safe %>
          };
    
          init(json);
      });
    </script>
    

    categories_helper.rb

      def category_to_spacetree_json(category)
        hash = {
          :id => category.id,
          :name => category.name,
          :data => '',
          :children => []
        }
    
        unless category.leaf?
          hash[:children] = category.children.public.collect { |c| category_to_spacetree_json(c) }
        end
    
        hash        
      end
    

    【讨论】:

      【解决方案2】:

      您可以编写自己的方法来返回所有后代,但是这是您使用的树类型效率很低的情况之一。

      如果您担心性能和数据库命中,您应该查看嵌套集 gem 之一,或 ancestry gem,它们是获取树枝的更有效方法。

      【讨论】:

        猜你喜欢
        • 2015-06-18
        • 2013-12-29
        • 1970-01-01
        • 2012-06-04
        • 2017-12-13
        • 1970-01-01
        • 2011-08-29
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多