Answer the question
In order to leave comments, you need to log in
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
Table "Categories"
create_table :categories do |t|
t.string :name, null: false, unique: true
t.integer :parent_id, index: true, foreign_key: true
end
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) }
# Что бы получить все основные категории
Category. parent_categories
# Получить подкатегории категории
Category.first.subcategories
# Получить товары категории
Category.first.items
"... 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 questionAsk a Question
731 491 924 answers to any question