使用Ruby on Rails创建分层的,optgrouped的下拉列表

时间:2012-11-06 21:34:24

标签: ruby-on-rails ruby

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

我有一个功能性的解决方案,但它很混乱。我有什么方法可以做这个整洁的?特别是对于辅助方法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

1 个答案:

答案 0 :(得分:0)

我会考虑在您的模型上使用awesome_nested_setActiveRecord Nesting category of Ruby Toolbox中的其他选项。他们有帮助器为您提供单个查询的整个树,有些甚至有Rails的视图助手。