产品和类别关系

试图在我的应用程序中具有以下关系。产品和类别关系

产品可以属于许多类别,子类别和子类别。

目前的设计:

Product: 

has_many :categorizations, dependent: :destroy

has_many :categories, through: :categorizations

has_many :sub_categories, through: :categorizations

has_many :sub_sub_categories, through: :categorizations

Category:

has_many :categorizations

has_many :products, through: :categorizations

has_many :sub_categories, class_name: 'Category', foreign_key: 'parent_id'

belongs_to :parent_category, class_name: 'Category', foreign_key: 'parent_id'

Categorization:

belongs_to :category

belongs_to :sub_category, class_name: 'Category', foreign_key: 'sub_category_id'

belongs_to :sub_sub_category, class_name: 'Category', foreign_key: 'sub_sub_category_id'

belongs_to :product

产品特定类别的可以被列为category.products

如何访问特定产品sub_categorysub_sub_category

我应该做些什么?

回答:

将此线路has_many :sub_sub_categories, through: :sub_categories添加到Product型号。

## app/models/product.rb 

has_many :sub_categories

has_many :categories, through: :sub_categories

has_many :sub_sub_categories, through: :sub_categories

如果我是你,我会设计这样的:

Product: 

has_many :categorizations

has_many :categories, through: :categorizations

Categorization:

belongs_to :product

belongs_to :category

Category:

belongs_to :parent, class_name: 'Category', optional: true

has_many :children, class_name: 'Category', foreign_key: :parent_id, dependent: :nullify

has_many :categorizations

has_many :products, through: :categorizations

注:添加parent_idcategories

以上是 产品和类别关系 的全部内容, 来源链接: utcz.com/qa/260128.html

回到顶部