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_categorysub_sub_category

我應該做些什麼?

回答

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_idcategories

+0

謝謝。和上面的設計是罰款或使用自引用關係在'category'而不是'sub_category'更好? – rAzOr

+0

看看我編輯的答案@rAzOr – fongfan999