繁体   English   中英

使用Ruby on Rails创建分层的,选择分组的下拉列表

[英]Creating a hierarchical, optgrouped, drop down list using Ruby on Rails

我正在尝试为Web应用程序创建一个下拉选择列表。 该列表必须具有optgroup,必须具有缩进(使用-- ),并且组名本身必须是选项。 由于optgrouping是一项要求,因此我需要使用group option helpers之一 由于所有内容都在一个模型中,因此我选择了grouped_options_for_select

我有一个功能性的解决方案,但很麻烦。 有什么办法可以使我更整洁? 特别是对于helper方法grouped_categories ,是否有更好的方法来创建嵌套数组,这样我就不需要多次调用数据库了?

风景;

<%= f.label :category_id %>
<%= f.select :category_id, grouped_options_for_select(grouped_categories.map{ |group| [group.first.name, group.second.map{|c| [c.name, c.id]}]}) %>

助手;

module CategoryHelper
 #building an array of elements (optgroup, members), where optgroup is one category object instance,
 # and members contains all category objects belonging to the optgroup, including the opt group object itself
 def grouped_categories
   @grouped_array = []
   Category.where("parent_id is null").each do |g|
     members = []
     members << g
     Category.where("parent_id = ?", g.id).each do |c|
       indent_subcategory(c)
       members << c
       Category.where("parent_id = ?", c.id).each do |s|
         indent_subsubcategory(s)
         members << s
       end
     end
     group = [g, members]
     @grouped_array << group
   end
   @grouped_array
 end

 def indent_subcategory(cat)
   cat.name = '--' + cat.name
 end

  def indent_subsubcategory(cat)
    cat.name = '----' + cat.name
  end
end

我会考虑在模型上使用awesome_nested_setRuby ToolboxActiveRecord Nesting类别中的其他选择。 他们有帮助者可以通过一个查询为您提供整个树,甚至有一些帮助有Rails的视图帮助者。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM