ruby-on-railsrubyruby-on-rails-5ancestry

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

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

and im getting like this

secret file1

my folder1

secret file2

my folder2

but my goal is to get the "my folder1" and "my folder2"


Solution

  • 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.