在下拉列表中显示树层次结构中的类别/子类别

我有一个包含字段id,name和parent_id的类别表。 根类别有parent_id 0.现在我想在下拉列表中显示类别列表,并显示如下结构:

root_category first_sub_category sub_sub_category another_sub_sub_category second_sub_category another_root_category first_sub_category second_sub_category 

这是我的控制器:

 def new @category = Category.new end 

以下是观点:

     

请帮忙。

通过在application_helper.rb中添加这些函数解决了这个问题

 def subcat_prefix(depth) (" " * 4 * depth).html_safe end def category_options_array(current_id = 0,categories=[], parent_id=0, depth=0) Category.where('parent_id = ? AND id != ?', parent_id, current_id ).order(:id).each do |category| categories << [subcat_prefix(depth) + category.name, category.id] category_options_array(current_id,categories, category.id, depth+1) end categories end 

并在我看来像这样使用它们

 <%= f.select(:parent_id, options_for_select(category_options_array), {}, class: 'form-control') %> 

假设你可以得到给定类别的孩子类似于:

 has_many :children, :class_name => 'Category', :foreign_key => 'parent_id' 

为类别创建一个方法以获取所有子级并按级别缩进:

 def all_children2(level=0) children_array = [] level +=1 #must use "all" otherwise ActiveRecord returns a relationship, not the array itself self.children.all.each do |child| children_array << " " * level + category.name children_array << child.all_children2(level) end #must flatten otherwise we get an array of arrays. Note last action is returned by default children_array = children_array.flatten end 

然后在你看来:

  

我没有100%测试这个,但我确实建议它应该工作......