2011-07-07 32 views
1

我正在嘗試使用sinatra和activereord創建一個在線商店(使用sinatra-activerecord寶石),並且我正在爲如何生成類別(子類和東西)的「樹」而煩惱。sinatra和activerecord的分類樹?

類別數據庫只包含類別名稱和PARENT_ID和activrecord模型如下:

class Category < ActiveRecord::Base 
    validates_presence_of :name 
    validates_uniqueness_of :name 

    has_many :sub_categories, :class_name => 'Category', 
    :foreign_key => 'parent_id', :dependent => :destroy 
    has_many :products, :dependent => :destroy 
    belongs_to :parent_category, :class_name => 'Category' 
end 

我將如何着手做這件事情我可以只在模板嵌套UL標籤(我使用哈姆,如果它有所作爲)?

對不起,我問這麼多,但我從來沒有真正使用這些數據結構。

+0

不應該是這樣的:'@sub = Category.find(...)。sub_categories'並且在模板中遍歷'@ sub'來顯示每個子類別。我不太確定,因爲我沒有使用ActiveRecord – daddz

+0

@daddz:我打算這樣做,但是這會將其限制爲有限的子類別。我寧願擁有它,所以無所謂多少類別(我認爲這意味着我想要一個遞歸類的東西,但我不知道) –

+0

只是列出子類別是不是更聰明目前「選定」類別?我想你的類別深度越高,請求的時間就越長,因爲每次都必須遍歷所有子類別。 – daddz

回答

0

我想通了。如果存在current_page,它使用HAML幫助程序並將current類應用於正確的元素。這裏的幫手

module Haml::Helpers 
    def categories_menu(parent=nil, current_page=false) 
    categories = Category.where(:parent_id => parent) 
    haml_tag :ul do 
     categories.each do |category| 
     haml_tag :li, :class => ("current" if current_page == category.id) do 
      haml_tag :a, :href => "/category/#{category.id}", :class => ("submenu" unless category.sub_categories.empty?) do 
      haml_concat(category.name) 
      end 
      unless category.sub_categories.empty? 
      categories_menu(category.id) 
      end 
     end 
     end 
    end 
    end 
end 

,你按如下方式使用它在一個HAML模板:

#test 
    - categories_menu(nil, (@category.id if defined? @category)) 

不能保證它會與其他人的應用工作。

相關問題