J.R.
J.R.

Reputation: 6059

Recursively iterate over nested structure

I have nested folder objects like a directory structure on a file system. A user could have:

and so on, as far down as the user wants. I am trying to display the folder structure as in above in a view.

I could do each on the first level, and for each folder in that level, do each on it's children, and then each on it's children and so on, manually. But that seems inefficient. I don't want there to be a pre-set limit to the levels. This seems something that should be automated, but I'm not quite sure how to do so. Furthermore, it seems recursion is not an option because there are no methods in a view.

Is this something a helper would be good for? Should I give up and only load a subfolder when the parent folder is clicked on, using javascript?

Upvotes: 0

Views: 596

Answers (2)

user1454117
user1454117

Reputation:

So assuming you have a Folder class with a subfolders method, you'll want to have a recursive partial, say _folder.html.erb:

<li><%= folder.name %></li>
<% unless folder.subfolders.empty? -%>
  <li>
    <ul>
      <%= render partial: "folder", collection: folder.subfolders %>
    </ul>
  </li>
<% end -%>

Then set some padding on your uls and you should be good to go.

The initial call to the partial would probably look something like this where @folders contains your top level folders and would live in a folders.html.erb or similar:

<ul>
  <%= render partial: "folder", collection: @folders %>
</ul>

Upvotes: 2

Michael Durrant
Michael Durrant

Reputation: 96544

Maybe something like:

class Folder < ActiveRecord::Base

  def self.add_in_children(folder)

    folder.children.each do |child|

      @all_folders << [level,child]
      @level+=1
      if child.children
        add_in_children(child)
      end
    end
  end 

  def self.all_records
    @all_folders=[]
    @level=0
    @folders=add_in_children('/')
  end

end

Folder.all_records;

Upvotes: 0

Related Questions