0
我正在嘗試爲Web應用程序創建一個下拉選擇列表。 此列表必須有optgroups,必須有縮進(使用--
),並且組名必須是選項本身。由於optgrouping是一項要求,我需要使用group option helpers之一。由於一切都在一個模型中,我選擇了grouped_options_for_select
。使用Ruby on Rails創建分層的optgrouped下拉列表
我有一個功能的解決方案,但它很凌亂。有什麼辦法可以讓這個整潔?特別是,對於輔助方法grouped_categories
,有沒有更好的方法來創建嵌套數組,以便我不需要多次調用數據庫?
The View;
<%= 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]}]}) %>
The Helper;
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