从ActiveRecord查询打印文件夹结构

坎农·莫耶

我有一个名为Folder的模型。该模型具有一个外键,该外键指向表的主键。我使用这种结构来创建虚拟文件夹树。

我的模型如下所示:

class Folder
     has_many :folders
     belongs_to :folder, optional: true
end

创建了几个相互关联的文件夹后,实际上创建了具有N个分支的树。我不记得应该如何解析它,以便可以在视图中打印出HTML,以显示实际的文件夹结构。

本质上,我的目标是查询所有没有父文件夹并从那里开始工作的文件夹,像这样。

@folders = Folder.all.where(folder_id: nil)

在我看来

<ul>
    <% @folders.each do |i| %>
        <li>
            <%= i.name %>
             Somehow I need to grab the other child folders here and continue this process N times.
        </li>
</ul>
格里科

您可以制作一个局部部分,以查看每个项目,然后1)将该项目渲染为常规li项目(如果该项目是文件),或者2)递归渲染自身(如果该项目是目录)。

例如:

# index.html.erb (or whatever your endpoint is, if not index)
<%= render partial: "_entries.html.erb", locals: {entries: @folders} %>

# _entries.html.erb
<ul>
  <% entries.each do |item| %>
    <li>
      <% if item.is_directory? %>
        <!-- rerender this partial with files in current directory -->
        <%= render partial: "_entries.html.erb", locals: {entries: item.children} %>
      <% else %>
        <!-- render individual items -->
        <%= item.name %>
      <% end %>
    </li>
  <% end %>
</ul>

ul最终应嵌套得尽可能深。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章