最近第一次开始使用rails和ancestry 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 %>有没有人能给点建议?
发布于 2016-09-15 23:04:51
你的孩子类别与他们的父母有什么关系?我假设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
endhttps://stackoverflow.com/questions/39514179
复制相似问题