在下拉列表中的树层次结构中显示类别/子类别 [英] Show categories/sub-categories in tree hierarchy inside a dropdown
本文介绍了在下拉列表中的树层次结构中显示类别/子类别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个包含字段 id、name 和 parent_id 的类别表.根类别的 parent_id 为 0.现在我想在下拉列表和如下结构中显示类别列表:
I have a category table with fields id,name and parent_id. The root categories have parent_id 0. Now i want to show the list of categories in a drop down and a structure like this:
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
这是视图:
<%= f.label :parent_category %>
<% categories = Category.all.map{|x| [x.name] + [x.id]} %>
<%= f.select(:parent_id, options_for_select(categories), {}, class: 'form-control') %>
请帮忙.
推荐答案
通过在application_helper.rb中添加这些函数解决了问题
Solved the problem by adding these functions in 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
并在我看来像这样使用它们
and using them in my view like this
<%= f.select(:parent_id, options_for_select(category_options_array), {}, class: 'form-control') %>
这篇关于在下拉列表中的树层次结构中显示类别/子类别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文