2010-05-17 45 views
2

我正在使用categoriesitems的軌道應用程序。嵌套在軌道中選擇

category模型是自接合,從而類別可以嵌套:

class Category < ActiveRecord::Base 
    has_many :items 

    # Self Join (categories can have subcategories) 
    has_many :subcategories, :class_name => "Category", :foreign_key => "parent_id" 
    belongs_to :parent,  :class_name => "Category" 
    ... 
end 

我有一個形式,它允許用戶創建一個item目前列出了全選類別,但他們都一起列出:

<%= f.label :category_id %> 
<%= select :item, :category_id, Category.all.collect {|c| [ c.title, c.id ]} %> 

所以選擇看起來是這樣的:

Category1 
Category2 
Category3BelongsTo2 
Category4BelongsTo1 

但我想要的是:

Category1 
    - Category4BelongsTo1 
Category2 
    - Category3BelongsTo2 

是否有這樣的助手(這將是真棒!)?如果不是,我怎麼能做到這一點?

謝謝!

回答

1

awesome_nested_set使這個小菜一碟。

安裝完成後,我將lftrgt添加到類別表中,並刪除了自加入。然後使用Category.rebuild!重建分類表。然後選擇可以像這樣容易地填充:

<%= f.select :parent_id, nested_set_options(Category, @category) {|c| "#{'-' * c.level} #{c.title}" } %>