Question

I've been doing a lot of research on what is the best approach to developing a schema for a new feature on a project I am working on.

I will have products that can be associated with an infinite number of categories and in infinite number of sub-categories.

As I started get frustrated I started to think that maybe I am just over thinking it. I'm wondering if the active record associations below make sense to you and you can foresee any possible gotchas.

class Product < ActiveRecord::Base
  has_many :categories
  has_many :sub_categories, through: :categories
end

class Category < ActiveRecord::Base
  belongs_to :product
  has_many :products
end

class SubCategory < ActiveRecord::Base
  belongs_to :category
end

No correct solution

OTHER TIPS

At this point, just go with what you have.

IF you start seeing a lot of overlap in both data and behavior (instance methods) or if you find yourself always wanting to access categories and sub categories together you could start looking at:

  1. Self joins - which would let you keep both categories in the same table and as the same type of model
  2. Ancestory - additional flexibility for a full-on tree structure of data
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top