When I went to a certain programming school and created a flea market app as a team, I implemented a multi-layered structure of categories, so I will introduce it! !!
Then I would like to introduce it.
First, I want to link products and categories, so I will create models for "category" and "item".
$ rails g model category
$ rails g model item
Introduce ancestory to Gemfile.
gem 'ancestry'
Execute the following command in the terminal
$ bundle install
$ rails g migration add_ancestry_to_category ancestry:string:index
$ rails db:migrate
By using ancestory, the many-to-many relationship becomes a one-to-many relationship and the DB design becomes simple.
Describe has_ancestory in category.rb
category.rb
class Category < ApplicationRecord
has_many :items
has_ancestry
end
item.rb
class Item < ApplicationRecord
belongs_to :category
end
We will introduce category records into seeds.rb.
seeds.rb
lady = Category.create(name: "Women")
lady_1 = lady.children.create(name: "tops")
lady_1.children.create([{name: "T-shirt/Cut and sew(Short sleeves/Sleeveless)"},{name: "T-shirt/Cut and sew(Seven minutes/Long sleeves)"},{name: "shirt/blouse(Short sleeves/Sleeveless)"},{name: "shirt/blouse(Seven minutes/Long sleeves)"},{name: "ポロshirt"},{name: "camisole"},{name: "Tank top"},{name: "Halter neck"},{name: "knit/sweater"},{name: "Tunic"},{name: "cardigan/Bolero"},{name: "ensemble"},{name: "Best/Gillet"},{name: "Parker"},{name: "trainer/sweat"},{name: "Bare top/Tube top"},{name: "Jersey"},{name: "Other"}])
If you include ancestry, you can treat it as a child element of the immediately preceding variable by writing .children.
The parent category, Ladies, is registered with the following description.
seeds.rb
lady = Category.create(name: "Women")
Next, the child category Tops is registered with the following description.
seeds.rb
lady_1 = lady.children.create(name: "tops")
Then, the grandchild category group is registered with the following description.
seeds.rb
lady_1.children.create([{name: "T-shirt/Cut and sew(Short sleeves/Sleeveless)"},{name: "T-shirt/Cut and sew(Seven minutes/Long sleeves)"},{name: "shirt/blouse(Short sleeves/Sleeveless)"},{name: "shirt/blouse(Seven minutes/Long sleeves)"},{name: "ポロshirt"},{name: "camisole"},{name: "Tank top"},{name: "Halter neck"},{name: "knit/sweater"},{name: "Tunic"},{name: "cardigan/Bolero"},{name: "ensemble"},{name: "Best/Gillet"},{name: "Parker"},{name: "trainer/sweat"},{name: "Bare top/Tube top"},{name: "Jersey"},{name: "Other"}])
After describing the record in seeds.rb, execute the following command in the terminal to reflect it in the DB.
$ rails db:seed
It is registered in DB like this.
Thank you for watching till the end! !!
I hope you found this article helpful: pray_tone2:
Recommended Posts