LoginSignup
2
0

More than 3 years have passed since last update.

【Rails】ancestryを用いた多階層カテゴリー機能の実装『seed編』

Last updated at Posted at 2020-06-19

開発環境

・Ruby: 2.5.7
・Rails: 5.2.4
・Vagrant: 2.2.7
・VirtualBox: 6.1
・OS: macOS Catalina

前提

下記実装済み。

投稿機能実装
多対多のカテゴリー機能実装
多階層カテゴリー機能実装(準備編)

実装

id name ancestry
1 ビジネス nil
2 金融 1
3 1/2
4 為替 1/2
5 税金 1/2
6 経済 2
7 日本経済 1/6
8 国際経済 1/6
9 経営 3
10 経営学 1/9
11 戦略・攻略 1/9
12 企業・開業 1/9
13 マーケティング 4
14 経営学 1/13
15 戦略・攻略 1/13
16 企業・開業 1/13

本のカテゴリーに上記の様な親子関係を持たせたい場合は、以下の様にデータを作成します。

seed.rb
business = Category.create(name: 'ビジネス')
business_children_array = ['金融', '経済', '経営', 'マーケティング']
business_grandchildren_array = [
  ['株', '為替', '税金'], # 金融の子
  ['日本経済', '国際経済'], # 経済の子
  ['経営学', '戦略・管理', '起業・開業'], # 経営の子
  ['広告', '営業', '開発'] # マーケティングの子
]

business_children_array.each_with_index do |children, index|
  children = business.children.create(name: children)
  business_grandchildren_array[index].each do |grandchildren|
    children.children.create(name: grandchildren)
  end
end

続編

多階層カテゴリー機能実装(作成フォーム編)

2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0