Rails: 枚举不同上下文视图中的数据

Rails: Enumerate data in the view with different context

我在我的应用程序中使用 awesome_nested_set gem 作为二叉树。

我需要在页面上显示二叉树。树中的每个节点都有一个按钮,显示两个下一个孩子。

我目前的代码不是 DRY,庞大且难以维护。 我得到当前用户的所有后代:

- users = current_user.descendants.unscope(:order).order(:depth, :lft)

每个级别和 "collaspsing zones" 必须有自己的 类。

#lvl-0
  .person-container
    .person-avatar
      = image_tag current_user.avatar_file_name, class: "img-circle avatar"
    .person-name
      %b
        = current_user.name
        = current_user.surname
  #lvl-1-left.lvl-child
    .person-container
      %span.badge(data-toggle="collapse" data-target="#lvl-2-left-from-left, #lvl-2-right-from-left")
        %span.caret
      .personal-avatar
        = image_tag users[0].avatar_file_name, class: "img-circle avatar"
      .personal-name
        %b
          = users[0].name  -# first child
          = users[0].surname
    #lvl-2-left-from-left.collapse.lvl-child
      .person-container
        %span.badge(data-toggle="collapse" data-target="THIS USER'S NEXT TWO CHILDREN")
          %span.caret
        .personal-avatar
          = image_tag users[2].avatar_file_name, class: "img-circle avatar"
        .personal-name
          %b
            = users[2].name
            = users[2].surname

    #lvl-2-right-from-left.collapse.lvl-child
      .person-container
        %span.badge(data-toggle="collapse" data-target="THIS USER'S NEXT TWO CHILDREN")
          %span.caret
        .personal-avatar
          = image_tag users[3].avatar_file_name, class: "img-circle avatar"
        .personal-name
          %b
            = users[3].name
            = users[3].surname

等等...

我想要这样的东西

- current_user.self_and_descendants.unscope(:order).order(:depth, :lft).each do |user|
  - case user.depth
  - when 0
    -# inject id and data-target, render _person.html.haml
  - when 1
    -# inject id and data-target, render _person.html.haml
  -# etc

你需要的是一个递归部分

创建部分 _nested_fields.html.haml 并添加

- users.each do |user|
  .person-container
    - if this user is not root
      %span.badge(data-toggle="collapse")
      %span.caret
    .personal-avatar
      = image_tag user.avatar_file_name, class: "img-circle avatar"
    .personal-name
      %b
        = user.name
        = user.surname

    - if this user has children
      = render "path_to_this/nested_fields", users: user.children

在您看来

= render "nested_fields", users: [current_user]

要添加缩进,您可以添加一些 css

.person-container {
  margin-left: 20px;
}