AdamGol
AdamGol

Reputation: 13

Ruby on Rails Creating categories and for each category, sub category and again for each sub category a sub sub category

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

Answers (2)

Muhammad Ali
Muhammad Ali

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

Hieu Pham
Hieu Pham

Reputation: 6707

Let try this gem

It helps easily create a hierarchy of models (like a tree). So in your case, you can use this gem to build a tree of category. Eg:

Category A has Category B, Category C
Category B has Category B1, Category B2
and so on!

Upvotes: 0

Related Questions