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 모델에 추가하십시오.

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 

참고 : 내가 당신이라면

## app/models/product.rb 
has_many :sub_categories 
has_many :categories, through: :sub_categories 
has_many :sub_sub_categories, through: :sub_categories 

,이 같은 설계 할 categories

+0

당신을 감사 테이블에 parent_id 추가 .. 그리고 디자인 위에 미세 또는 자기 참조 관계를 사용하고 'sub_category' 대신'category'에있는 것이 더 낫습니다. – rAzOr

+0

내 편집 된 답변보기 @rAzOr – fongfan999