使用after_create

时间:2011-02-04 20:09:09

标签: ruby-on-rails-3 active-relation

我有一个模特,类别。我想在创建类别时创建一个新的默认sub_category。但我不知道该怎么做。这就是我所拥有的。

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

1 个答案:

答案 0 :(得分:3)

为什么不使用ancestry gem?将来,如果你有更多的子类别,管理它们会更容易。

例如在您的情况下:

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

但是你能解释一下,为什么你需要这么奇怪的默认行为?

由于