简体   繁体   中英

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?

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.

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM