2011-02-04 60 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

相关问题