【问题标题】:Ruby: acts_as_tree to nested hashes (arrays of hashes)Ruby:acts_as_tree 到嵌套散列(散列数组)
【发布时间】:2010-09-04 04:47:21
【问题描述】:

我正在尝试找出一种优雅的方式来“绘制”出使用acts_as_tree 定义的任意树结构。我的最终目标是将父/子关系转换为可以转换为 Yaml 文件的嵌套哈希。

示例树:

root
--child
--child
----subchild
----subchild
------anotherchld
--child
--child
----subchild
------anotherhchild
--child

我希望它产生这个:

{'root' => 
  [{'child' => nil },
   {'child' => 
     [{'subchild' => nil },
     {'subchild' => nil }]},
...
]}

也许这不是最好的方法?您能否为我提供一种转换树的替代方法,使其或多或少类似于上面的文本,但作为 Yaml?

【问题讨论】:

    标签: ruby-on-rails ruby


    【解决方案1】:

    啊,递归:

    require 'yaml'
    
    class Category (or whatever)
      def to_hash
        {@name => @children.empty? ? nil : @children.map {|child| child.to_hash}}
      end
    end
    
    puts root.to_hash.inspect
    puts
    puts root.to_hash.to_yaml
    

    这给了我:

    {"root"=>[
      {"child 1"=>nil},
      {"child 2"=>[
        {"subchild 1"=>nil},
        {"subchild 2"=>[
          {"subsubchild 1"=>nil}
        ]}
      ]},
      {"child 3"=>nil},
      {"child 4"=>[
        {"subchild 3"=>[
          {"subsubchild 2"=>nil}
        ]}
      ]},
      {"child 5"=>nil}
    ]}
    
    root: 
    - child 1: 
    - child 2: 
      - subchild 1: 
      - subchild 2: 
        - subsubchild 1: 
    - child 3: 
    - child 4: 
      - subchild 3: 
        - subsubchild 2: 
    - child 5: 
    

    怎么样?

    【讨论】:

      【解决方案2】:

      我不知道我是否正确理解了你的问题,但如果你正在寻找一种算法来生成(yaml)输出树,你可能想看看at this question(它也相关awesome_nested_set,但我认为它应该可以修改它以使用acts_as_tree)。

      【讨论】:

        猜你喜欢
        • 2013-03-14
        • 1970-01-01
        • 2018-11-07
        • 1970-01-01
        • 2012-03-27
        • 2016-08-10
        • 2014-07-28
        • 2013-07-08
        • 1970-01-01
        相关资源
        最近更新 更多