0

试图在我的应用程序中建立以下关系。

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

当前设计:

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_category和的产品sub_sub_category

我应该做些什么改变??

4

1 回答 1

0

将此行添加has_many :sub_sub_categories, through: :sub_categoriesProduct模型中。

## 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_id到表格categories

于 2017-12-03T09:06:01.467 回答