产品和类别关系

时间:2017-12-03 08:51:13

标签: ruby-on-rails ruby-on-rails-4 foreign-keys associations self-referencing-table

尝试在我的申请中建立以下关系。

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

当前设计:

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的产品?

我应该做些什么改变?

1 个答案:

答案 0 :(得分:0)

将此行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_id添加到表格categories