尝试在我的申请中建立以下关系。
产品可以属于多个类别,子类别和子子类别。
当前设计:
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
的产品?
我应该做些什么改变?
答案 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