Ruby on Rails为每个子类别和每个子类别创建类别和子类别

时间:2016-03-24 03:39:11

标签: ruby-on-rails

我有一个问题,如果有人能帮助我,我感激不尽。我正在研究一个项目,需要为每个类别和子类别创建类别,并为每个子类别再次创建子子类别。它就像瀑布......对此最好的解决方案是什么?我是否需要为每个模型创建一个模型并将它们相互链接,或者您可以提供更好的解决方案?

2 个答案:

答案 0 :(得分:1)

我会使用自我继承+多态和一个包含多个模型的表。

如下:

类别型号:

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

子类别模型:

class SubCategory < Category
  has_many :sub_sub_categories , :class_name => "SubSubCategory" , :as => :parent , :dependent => :destroy
end

SubSubCategory [您可以更改最适合您的型号名称。]

class SubSubCategory < Category
  has_many :items , :class_name => "Item", :foreign_key => :category_id, :dependent => :destroy
end

这将是您正在寻找的解决方案。希望它会有所帮助。

答案 1 :(得分:0)

试试这个gem

它有助于轻松创建模型层次结构(如树)。因此,在您的情况下,您可以使用此gem来构建类别树。例如:

Category A has Category B, Category C
Category B has Category B1, Category B2
and so on!
相关问题