加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – 在下拉列表中的树结构中显示类别/子类别

发布时间:2020-12-16 22:44:26 所属栏目:百科 来源:网络整理
导读:我有一个具有字段id,name和parent_id的类别表.根类别有parent_id 0.现在我想在一个下拉列表中显示类别列表,并显示如下结构: root_category first_sub_category sub_sub_category another_sub_sub_category second_sub_categoryanother_root_category first_
我有一个具有字段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

这里的看法:

<%= 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中添加这些函数来解决问题
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

并在我看来使用它们

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读