简体   繁体   English

rails 祖先通过根获取所有最后一个孩子

[英]rails ancestry get the all last children by the root

i have this record in Folder class我在文件夹类中有这个记录

Folder 1 = parent id: root
  sub folder 1 = parent id: Folder 1
    secret file1 = parent id: Folder 1/sub folder 1
      my folder1 = parent id: Folder 1/ sub folder 1/ secret file1

Folder 2
 sub folder 2 = parent id: Folder 2
  secret file2 = parent id: Folder 2/sub folder 2
   my folder2 = parent id: Folder 2/ sub folder 2/ secret file2

now i have this in my html现在我的 html 中有这个

- folder.indirects.each do |sub|
   div.col
    div.form-group
     = sub.name

and im getting like this我变得像这样

secret file1秘密档案1

my folder1我的文件夹1

secret file2秘密文件2

my folder2我的文件夹 2

but my goal is to get the "my folder1" and "my folder2"但我的目标是获得“我的文件夹1”和“我的文件夹2”

So you basically want to get all leaf nodes, right?所以你基本上想要获取所有叶节点,对吗?

You can do it by iterating through all descendants and rejecting nodes with children.您可以通过遍历所有后代并拒绝带有孩子的节点来实现。 It might not be the most performant solution but it will work.它可能不是性能最高的解决方案,但它会起作用。

 - folder.descendants.reject(&:has_children?).each do |sub|
   div.col
    div.form-group
     = sub.name

BTW using the indirects method is wrong for trees with level = 2, because in this case you'd be rejecting root's direct children, which are also leafs in this case.顺便说一句,对于级别= 2 的树,使用indirects方法是错误的,因为在这种情况下,您将拒绝根的直接子级,在这种情况下它们也是叶子。

- folder.indirects.each do |sub|
  - if sub.children.blank?
    div.col
      div.form-group
       = sub.name

i use if so i can rid the other folder我使用 if so 我可以删除另一个文件夹

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM