最近尝试了下 mongoid-tree,觉得挺好用,可以实现无限级分类,顺便写了一个 helper,来帮助在页面展示分类的下拉菜单,看代码: category.rb
#coding:utf-8
class Category
include Mongoid::Document
include Mongoid::Tree
field :name, type: String
field :state, type: Integer, default: 0
field :content, type: String
def get_tree(tree)
if self.root?
tree << ["#{self.name}","#{self.id}"]
else
level = self.depth #level表示当前分类是第几级分类(0代表顶级,依次类推)
bloc = " " * level #这里的空格是英文全角空格
tree << [ bloc + "|--#{self.name}","#{self.id}"]
end
if self.children?
self.children.each do |chi|
chi.get_tree(tree)
end
end
end
end
application_helper.rb
module ApplicationHelper
def category_tree
tree = []
Category.roots.each do |cate|
cate.get_tree(tree)
end
return tree
end
end
_form.html.erb
<div class="control-group">
<%= f.label :parent_id, :class => 'control-label' %>
<div class="controls">
<%= f.select :parent_id,category_tree,{:include_blank => '顶级分类'}%>
</div>
</div>
效果图如下: