J
J
JIuc75Rus2017-01-26 00:40:08
Ruby on Rails
JIuc75Rus, 2017-01-26 00:40:08

How to implement the category structure in Ruby on Rails, subcategories, subcategories of product categories, and the products themselves in product categories?

The essence of the task is this - there is a main category, let's say this is electronics, there is also a sub-category, let it be Samsung and there are categories of goods in it - phones, TVs, etc. and, accordingly, the goods themselves. And in some subcategories certain categories of goods may be missing. What relationships to use for models? How to properly organize a database? How to display all this in views?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexander Leonchik, 2017-01-26
@JIuc75Rus

Table "Categories"

create_table :categories do |t|
  t.string  :name, null: false, unique: true
  t.integer :parent_id, index: true, foreign_key: true
end

In the table "Products / Items" add:
Model "Categories":
has_many :items, dependent: :destroy

has_many   :subcategories,   class_name: 'Category', foreign_key: :parent_id, dependent: :destroy
belongs_to :parent_category, class_name: 'Category', foreign_key: :parent_id

scope :parent_categories, -> { where(parent_id: nil) }

Model "Products"
# Что бы получить все основные категории
Category. parent_categories

# Получить подкатегории категории
Category.first.subcategories

# Получить товары категории
Category.first.items

A
Anton, 2017-01-26
@hummingbird

"... how to write code?" - this should also have been added to the end of your text.
Seriously though, add the parent_id field to the categories table . The default is zero (no parent category). I think everything is clear here. Well, then has_many in the Category model and belongs_to in Product . You can read about them (with examples) here: guides.rubyonrails.org/association_basics.html And in general...
Well, this is generally some kind of scumbag. Are you talking about cycles or what?
Also useful:
guides.rubyonrails.org/active_record_querying.html

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question