0

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
Antarr Byrd
  • 24,863
  • 33
  • 100
  • 188

1 Answers1

3

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

Dmitry Polushkin
  • 3,283
  • 1
  • 38
  • 44