How to model product categories?


I'm about to start developing an e-commerce, but I'm caught up in the issue of modeling, especially in product categories and subcategories. For example. A category can have several sub-categories. Each sub-category may also have sub-sub-categories (maximum of 3 levels). More or less like this:

--Sub Categoria
---Sub-sub categoria

What would that look like in the database? Was it a self-relationship? If yes, or if not, can someone give an example?

Another doubt. Example:

-- Camisetas
  -- Masculino
   ---- Camiseta M. pollo tam. G (produto)

If this shirt belongs to men, then it automatically percends the shirts and apparel. I will use Rails, how would I implement this kind of behavior there?

asked by anonymous 18.09.2014 / 18:53

1 answer


Just use a recursive reference in creating the Category model and create a level counter to limit to 3.

class Category < ActiveRecord::Base
  has_many :products
  belongs_to :parent, class_name: "Category", foreign_key: "category_id"
  has_many :children, class_name: "Category", foreign_key: "category_id"

  # Valida para ser no máximo do terceiro nível (começa em zero)
  validates :level, :numericality => { :less_than_or_equal_to => 2 }

  # verifical dinâmicamente o nível da categoria
  def level
    parent.nil? ? 0 : parent.level + 1

In the Product model, reference the Category model

class Product < ActiveRecord::Base
  belongs_to :category

Regarding the database, the structure of the tables is as follows:

Table: Categories

id (pk)
category_id (fk)

Table: Products

id (pk)
category_id (fk)
19.09.2014 / 14:41