2015-09-07 16 views
9

Tôi có bảng danh mục có id trường, tên và parent_id. Các loại rễ đã PARENT_ID 0. Bây giờ tôi muốn hiển thị danh sách các mục trong một danh sách thả xuống và một cấu trúc như thế này:Hiển thị danh mục/danh mục con trong phân cấp cây bên trong menu thả xuống

Dưới đây là bộ điều khiển của tôi:

def new 
    @category = Category.new 
end 

Và đây là quan điểm:

<%= f.label :parent_category %> 
    <% categories = Category.all.map{|x| [x.name] + [x.id]} %> 
    <%= f.select(:parent_id, options_for_select(categories), {}, class: 'form-control') %> 

Vui lòng trợ giúp.

Trả lời

10

giải quyết vấn đề bằng cách thêm các chức năng này trong 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 

và sử dụng chúng trong quan điểm của tôi như thế này

<%= f.select(:parent_id, options_for_select(category_options_array), {}, class: 'form-control') %> 
3

Giả sử bạn có thể nhận được những đứa trẻ của một thể loại nhất định tương tự như:

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

Tạo một phương pháp để loại để có được tất cả trẻ em và thụt mỗi bởi mức:

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 

Sau đó, trong bạn chế độ xem:

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

Tôi chưa thử nghiệm 100% nhưng các bit tôi đã đề xuất sẽ hoạt động ...

Các vấn đề liên quan