2011-02-04 54 views
0

我有一個模型,類別。我想創建一個新的默認sub_category時,創建類別。但我不知道該怎麼做。這是我的。使用after_create

class Category < ActiveRecord::Base 
    attr_accessible :title, :position 

    has_many :sub_categories 

    after_create :make_default_sub 

    def make_default_sub 
     #Sub_Categories.new(:title=>' '); 
    end 
end 

回答

3

爲什麼不使用ancestry寶石?將來如果你有更多的子類別,管理它們會更容易。

例如你的情況:

class Category < ActiveRecord::Base 
    attr_accessible :title, :position 

    has_ancestry 

    after_create :create_default_subcategory 

    def make_default_sub 
     children = self.children.new 
     children.title = '' 
     children.position = 1 # or autogenerated 
     children.save! 
    end 
end 

但是你可以解釋,爲什麼還需要這樣一個奇怪的默認行爲?

感謝

+0

我所有的廣告屬於子類別不分類 – 2011-02-04 21:49:31

相關問題