0

Webアプリケーションのドロップダウン選択リストを作成しようとしています。このリストにはoptgroupsが必要であり、(を使用して--)インデントが必要であり、グループ名はそれ自体がオプションである必要があります。optgroupingは必須であるため、グループオプションヘルパーの1つを使用する必要があります。すべてが1つのモデルに含まれているため、を選択し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
4

1 に答える 1

0

モデルで Ruby Toolbox の ActiveRecord Nesting カテゴリをawesome_nested_set使用するか、その他の選択を検討します。単一のクエリでツリー全体を表示するヘルパーがあり、Rails 用のビュー ヘルパーを持っているものもあります。

于 2012-11-06T22:47:58.750 に答える