Home Product and Category relationship
Reply: 1

Product and Category relationship

rAzOr
1#
rAzOr Published in 2017-12-03 08:51:12Z

Trying to have following relationship in my application.

Product can belong to many categories, sub categories and sub sub categories.

Current design:

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

products of a particular category can be listed as category.products.

How to access products of a particular sub_category and sub_sub_category?

What changes should I make??

Phong Phan
2#
Phong Phan Reply to 2017-12-03 10:59:23Z

Add this line has_many :sub_sub_categories, through: :sub_categories to the Product model.

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

If I were you, I would design like this:

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

Note: Add parent_id to table categories

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.250964 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO