2015-09-07 11 views
9

के अंदर पेड़ पदानुक्रम में श्रेणियों/उप श्रेणियों को दिखाएं मेरे पास फ़ील्ड आईडी, नाम और parent_id के साथ एक श्रेणी तालिका है। जड़ श्रेणियों PARENT_ID है 0. अब मैं एक ड्रॉप डाउन में श्रेणियों की सूची दिखाने के लिए करना चाहते हैं और इस तरह की एक संरचना:एक ड्रॉपडाउन

यहाँ मेरी नियंत्रक है:

def new 
    @category = Category.new 
end 

और यहाँ दृश्य है:

<%= 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

इस

<%= f.select(:parent_id, options_for_select(category_options_array), {}, class: 'form-control') %> 
की तरह मेरे विचार में 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 

में इन कार्यों को जोड़ने और उन्हें का उपयोग करके समस्या हल

3

मान लें कि आप के लिए इसी तरह किसी एक श्रेणी के बच्चों को प्राप्त कर सकते हैं:

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

एक विधि बनाएं श्रेणियों के सभी बच्चों के लिए और स्तर से प्रत्येक को इंडेंट करने के लिए: में फिर

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 

अपने देखें:

<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% परीक्षण नहीं किया है, लेकिन बिट्स मैंने सुझाव दिया है कि यह काम करना चाहिए ...

संबंधित मुद्दे