Using after_create

2.2k Views Asked by At

I have a model, Category. And I want to create an new default sub_category when ever the category is created. But I'm not sure how to do it. Here is what I have.

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

There are 1 best solutions below

2
Dmitry Polushkin On BEST ANSWER

Why not to use ancestry gem? In the future if you will have more subcategories, it will be easier to manage them.

For example in your case:

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

But can you explain, why do you need such a strange default behaviour?

Thanks