3
0

More than 3 years have passed since last update.

【Rails】ancestryで簡単に多階層型データの作成し呼び出す

Posted at

概要

・多階層型DB作成のためのgem "ancestry" の導入
・seeds.rbでのデータインプット効率化
・viewファイルへの表示

階層型DB作成のためのgem "ancestry" の導入

gemの導入

Gemfile
gem 'ancestry'
ターミナル
$ bundle install
$ rails g migration add_ancestry_to_category ancestry:string:index
$ rake db:migrate

モデルの設定

categories_controller.rb
class Category < ApplicationRecord
    has_many :items
    has_ancestry
end
items_controller.rb
class Item < ApplicationRecord
    belongs_to :category
end

データの追加

seeds.rb
drink = Category.create(name: "飲み物")

drink_juice = juice.children.create(name: "ジュース")

drink_juice.children.create([{name: "オレンジ"}, {name: "アップル"}, {name: "グレープ"}])
ターミナル
% rails db:seed

seeds.rbでのデータインプット効率化

数件、数十件レベルのデータ量であれば、上記「データの追加」でも問題ありませんが、
それ以上の膨大なデータを作成するのであれば、以下の方法で効率的に作成しましょう。

seeds.rb
@category1 = Category.create(name:"飲み物")

category1s = [
             {level2:"ジュース",level2_children:["オレンジジュース","コーラ","サイダー"]},
             {level2:"お酒",level2_children:["ビール","ハイボール","焼酎","ワイン"]}, 
             {level2:"お茶",level2_children:["緑茶","烏龍茶","ほうじ茶","はとむぎ茶"]},
            ]
category1s.each.with_index(1) do |category1,i|
  level2_var="@category1_#{i}"
  level2_val= @category1.children.create(name:"#{category1[:level2]}")
  eval("#{level2_var} = level2_val")
  category1[:level2_children].each do |level2_children_val|
    eval("#{level2_var}.children.create(name:level2_children_val)")
  end
end
ターミナル
% rails db:seed

これでデータベースに反映されるはずです。

子要素の呼び出し

親要素.children

親要素の呼び出し

子要素.parent

以上です。
最後まで読んでいただきありがとうございました。

3
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
3
0