在下拉菜单中显示树状层次结构中的类别/子类别 [英] Show categories/sub-categories in tree hierarchy inside a dropdown

查看:85
本文介绍了在下拉菜单中显示树状层次结构中的类别/子类别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有字段id,名称和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


$ b

这是我的控制器:

  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')%>

请帮助。

解决方案

  def subcat_prefix(深度)$ b $解决了这个问题b(& nbsp;* 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 |
类别<< [subcat_prefix(depth)+ category.name,category.id]
category_options_array(current_id,categories,category.id,depth + 1)
end

类别
结束

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

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


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

Here's my Controller:

def new
  @category = Category.new
end   

And here's the view:

    <%= f.label :parent_category %>
    <% categories = Category.all.map{|x| [x.name] + [x.id]} %>
    <%= f.select(:parent_id, options_for_select(categories), {}, class: 'form-control') %>

Please Help.

解决方案

Solved the problem by adding these functions in application_helper.rb

def subcat_prefix(depth)
  ("&nbsp;" * 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆