shimmyShow Webアプリ開発ブログ

プログラミングスクールTECH::CAMPを73期を卒業し、紙媒体で実施されている教育の根本を変えていくためのサービスを開発中。当ブログを読めば誰でも当該サービスを開発できるようにするため軌跡を記録中。

【Ruby on Rails】gem 'ancestry'を使用する際のseedによる初期データ登録

Ruby on Railsにおいて、gem 'ancestry'を使用したテーブルへの初期データ登録にseedを活用する場合に create文を大量に記述する必要が生じる。 下記Qiitaの参考記事をもとにcreate文の記述量をできるだけ抑えたseedの記述方法を下記に示す。

概要

ancestry(親・子・孫)を活用したテーブルへの初期データ(大量)の実装

具体例

下記例は、ancestryを活用したtextsテーブルへのデータ登録処理(seeds.rb)の例  親:高等学校数学の大分類(例:数学ⅠA)  子:大分類の中の項目(例:集合と論理や2次関数など)  孫:項目の内容(例:集合の基本や部分集合、2次関数のグラフ、平方完成など)

テーブル定義(マイグレーションファイル)

class CreateTexts < ActiveRecord::Migration[5.2]
  def change
    create_table :texts do |t|
      t.text     :content,        null:false
      t.string     :ancestry
      t.timestamps
    end
  end
end

seeds.rb

#######################################
# テキストテーブルへのデータ登録処理
#######################################

def createChildAndGrandChildren(parentArray, childArray, grandChildrenArray)
  childArray.each_with_index do |child, i|
    child = parentArray.children.create(content: child)
    grandChildrenArray[i].each do |grandchild|
      child.children.create(content: grandchild)
    end
  end
end

#######################################
# 初期データ定義
#######################################

# 数学ⅠAの子カテゴリー
mathmatics_1A     = Text.create(content: '数学ⅠA')
# 数学ⅠAの子カテゴリー
mathmatics_1A_child = ["数と式","集合と論理","2次関数"]
#数学ⅠAの孫カテゴリー
mathmatics_1A_grand_children = [
  # 数と式
  ["次数は文字を掛けた回数のこと","指数法則を使いこなす","有理数と無理数","3つの連立方程式"],
  # 集合と論理
  ["集合の基本","部分集合","否定","逆, 裏, 対偶"],
  # 2次関数
  ["2次関数のグラフ","平方完成","平行移動","解の条件"]
]

# 数学ⅡBの親カテゴリー
mathmatics_2B     = Text.create(content: '数学ⅡB')
# 数学ⅡBの子カテゴリー
mathmatics_2B_child = ["複素数と方程式","三角関数","微分"]
# 数学ⅡBの孫カテゴリー
mathmatics_2B_grand_children = [
  # 複素数と方程式
  ["複素数の計算","剰余の定理","高次方程式","3乗して1になる虚数"],
  # 三角関数
  ["弧度法","加法定理","合成","三角関数の最大と最小"],
  # 微分
  ["極限","導関数"]
]

#######################################
# 初期データ登録
#######################################
createChildAndGrandChildren(mathmatics_1A, mathmatics_1A_child, mathmatics_1A_grand_children);
createChildAndGrandChildren(mathmatics_2B, mathmatics_2B_child, mathmatics_2B_grand_children);

実行コマンド

テーブルが空の場合、下記resetコマンドは不要

rails db:migrate:reset
rails db:seed

コマンド実行後テーブル

f:id:erwinmarvin:20200822145317p:plain
Texts table 初期データ登録
 

参考記事

 下記Qiita記事を参考に登録処理部分の関数化を実施  参考記事の説明が非常にわかりやすい為、上記処理を理解するためには一読すべきです。 qiita.com