2015-09-07 9 views
9

フィールドID、名前、および親IDを持つカテゴリテーブルがあります。ツリー階層のカテゴリ/サブカテゴリをドロップダウン内に表示

ここに私のコントローラの:

def new 
    @category = Category.new 
end 

そして、ここでは、ビューです:

ルートカテゴリは、私がドロップダウンにカテゴリのリストを表示したいと、このような構造は、今すぐ0にPARENT_IDています
<%= f.label :parent_category %> 
    <% categories = Category.all.map{|x| [x.name] + [x.id]} %> 
    <%= f.select(:parent_id, options_for_select(categories), {}, class: 'form-control') %> 

お願いします。

答えて

10

は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') %> 
のように私の見解では、それらを使用して、これらの機能を追加することで問題を解決しました
3

あなたがに似て特定のカテゴリの子供を取得することができますと仮定すると:あなたに続いて

def all_children2(level=0) 
    children_array = [] 
    level +=1 
    #must use "all" otherwise ActiveRecord returns a relationship, not the array itself 
    self.children.all.each do |child| 
     children_array << "&nbsp;" * level + category.name 
     children_array << child.all_children2(level) 
    end 
    #must flatten otherwise we get an array of arrays. Note last action is returned by default 
    children_array = children_array.flatten 
end 

has_many :children, :class_name => 'Category', :foreign_key => 'parent_id' 

は、すべての子を取得し、レベルによってそれぞれをインデントするカテゴリのメソッドを作成します。表示:

<select> 
    <option></option> 
    <% root_categories.each do |category| %> 
     <option><%=category.name%></option> 
     <% category.all_children2.each do |child| %> 
     <option><%=child.html_safe%></option> 
     <% end %> 
    <% end %> 
</select> 

私はこれを100%テストしていませんが、私はそれがうまくいくはずです...