How to model product categories?

Asked

Viewed 802 times

4

I am about to start the development of an e-commerce, but I am focused on the issue of modeling, especially regarding categories and subcategories of products. For example. A category can have several sub-categories. Each sub-category can also have sub-categories (maximum of 3 levels). Sort of like this:

-Categoria
--Sub Categoria
---Sub-sub categoria

How would that look in the database? Would it be a relationship? If yes, or if not, someone can give an example?

Another question. Example:

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

If this T-shirt belongs to men, then it automatically perceives T-shirts and clothing. I will use Rails, as I would implement this kind of behavior there?

  • I don’t know Rails, but I think the concept of scaffolding of it may be useful.

  • 1

    See if this helps: link

  • I would make a table of categories with self-relationship allowing n subcategories, the relationship with products would be something of the product-<product_category>----category , trying to summarize .... (1) Refrigerant category, sub-glues , sub-sugar-free /// (2) Non-dietetics category , sub-refrigerants , the product Motta-glue-on categories (1) and (2)

  • 2

    About the modeling part of the database, see How to model a tree data structure using a relational database?. About doing this in Rails I didn’t find much here on the site, but maybe this be a start.

  • @Motta Your comment is almost an answer, missing only a little detail.

  • @Andrey , I will try to detail how to answer, but the kind of question that does not have a single answer.

Show 1 more comment

1 answer

3

Just use a recursive reference when 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
  end
end

and in the Product model, reference the Category model

class Product < ActiveRecord::Base
  belongs_to :category
end

Regarding the database, the structure of the tables was the following:

Table: Categories

id (pk)
name
category_id (fk)

Table: Products

id (pk)
name 
category_id (fk)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.