【问题标题】:Iterating in ruby using an if else statement ...(along w. ancestry gem)使用 if else 语句在 ruby​​ 中迭代 ...(沿着 w. ancestry gem)
【发布时间】:2016-09-15 14:51:16
【问题描述】:

最近第一次使用railsancestry gem。

我正在尝试通过 ancestry gem 遍历存储在树结构中的 Category 对象数组,以便显示按钮,连接到 link_to 到其他类别对象,给定类别是相关。

数据库中的前 3 个类别是根,因此我最终将没有足够的空间在视图中显示所有后代的按钮。所以,如果category.parent == 'nil',我想只显示给定类别的孩子。

但是,对于所有其他类别对象,我想显示给定类别的所有后代。

我在想一些类似的事情,以迭代

<%= current_user.folders.each do |folder| %>
  <% if folder.is_root? %>
    <% folder.children.each do |child| %>
      <%= link_to child, folder_path(child), class: 'btn' %>
    <% end %>
  <% else %>
    <% folder.descendants.each do |desc| %>
      <%= link_to desc, folder_path(desc), class: 'btn' %>
  <% end %>
<% end %>

谁能给点建议?

【问题讨论】:

    标签: ruby-on-rails ruby ancestry


    【解决方案1】:

    您的孩子类别与他们的父母有什么关系?我假设categories 表有一个parent_id 列。

    鉴于这些类别:

    parent_category = Category.create!
    child_category1 = Category.create! parent_id: parent_category.id
    child_category2 = Category.create! parent_id: parent_category.id
    

    现在您可以检查parent_id 是否为nil 以查看它是否是父类别,我们将为Category 模型添加自引用关联和范围:

    class Category < ActiveRecord::Base
      scope :parents, -> { where(parent_id: nil).joins :children }
      has_many :children, class_name: "Category", foreign_key: :parent_id
    end
    

    现在您可以遍历父级并遍历每个父级的子级:

    Category.parents.each do |parent|
      parent.children.each do |child|
        # code
      end
    end
    

    【讨论】:

    • 我基本上已经完成了...但是,我很难弄清楚如何根据给定类别对象的 id 进行迭代... tx 为您的响应 diego,它是赞赏...
    • ancestry gem 的工作原理与我上面解释的完全一样。不确定“根据给定类别的 id 遍历”是什么意思。使用id,您可以找到类别category = Category.find id,然后祖先gem 为您提供children 方法category.children。它有很多用于导航对象树的方法github.com/stefankroes/ancestry#navigating-your-tree
    • is_root? Ancestry 中的方法是您正在寻找的。​​span>
    • 啊,在编辑帖子以包含代码后,请阅读您的评论。也许,我应该用 'if folder.is_root?' 替换行 'if folder.parent == 'nil', 看看是否可行。任何其他建议,w。尊重代码?不胜感激:-) ...
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-08-22
    • 2019-04-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多