Reputation: 13
I've got a question and I appreciate if anyone could help me please. I'm working on a project and need to create categories and for each category, sub category and again for each sub category a sub sub category. It's like waterfall... What is the best solution for that? Do I need to create a model for each one and chain them to each other or you may offer a better solution?
Upvotes: 0
Views: 1251
Reputation: 2183
I would do it with self-inheritance + polymorphism and one table with multiple models.
like Below :
Category Model :
class Category < ActiveRecord::Base
self.inheritance_column = :child_class
has_many :disabled_category_business_types
has_many :sub_categories, :class_name => 'SubCategory', :foreign_key => :parent_id, :as => :parent
belongs_to :parent, :polymorphic => true
def all_categories
Category.where(:parent_type => 'System')
end
def all_subcategories
Category.where(:child_class => 'SubCategory')
end
def all_subsubcategories
Category.where(:child_class => 'SubSubCategory')
end
def child_ids
return self.sub_category_ids if self.child_class == 'Category'
return self.sub_sub_categories if self.child_class == 'SubCategory'
end
end
SubCategory Model :
class SubCategory < Category
has_many :sub_sub_categories , :class_name => "SubSubCategory" , :as => :parent , :dependent => :destroy
end
SubSubCategory [You can change model name as suits you best.]
class SubSubCategory < Category
has_many :items , :class_name => "Item", :foreign_key => :category_id, :dependent => :destroy
end
This will be the solution you are looking for. Hope it will help.
Upvotes: 1