2
0

More than 3 years have passed since last update.

【Ruby on Rails】初期データの導入

Posted at

はじめに

動作確認の為の初期データを投入することで、
DBをリセットした場合に、seedファイルを基に初期データを再び作成できたり、
一度に大量のデータを作成する事ができるため、
開発段階のアプリケーションには必要な機能となります。

今回はseedファイルを編集して、初期データを投入します。

開発環境

ruby 2.5.7
Rails 5.2.4.3
OS: macOS Catalina

seedファイルとは

rails new 〇〇コマンドを実行した時に作成されるファイルでdbディレクトリの直下にあります。
db/seeds.rb

実際に作成する

db/seeds.rb
# This file should contain all the record creation needed to seed the database with its default values.
# The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup).
#
# Examples:
#
#   movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }])
#   Character.create(name: 'Luke', movie: movies.first)
User.create!(
   email: 'test@tesr.com',
   password: 'testpass',
)
Post.create!(
   title: 'よろしくお願いします',
   content: 'seedファイルについて',
)

データベースに反映

ターミナル
$ rails db:seed

これでuserのログインも可能になり、Postにはデータが投入されました。
その後確認方法としては、下記のように実行して
データが入っていれば成功です。

ターミナル
$ rails c
pry(main)> Post.all

複数ファイルを作成する場合

for文と内容はにており、指定した回数文処理を繰り返します。
初期数字は0から始まるため、下記の場合は0-9となります。

db/seeds.rb
  Post.create!(
    title: 'よろしくお願いします',
    body: 'seedファイルについて'
  )

  10.times do |number|
    List.create!(title: 'timesについて',body: number)
  end

まとめ

この他にもcsvからデータの投入方法がありますので、
興味のある方は調べてみてください。

またtwitterではQiitaにはアップしていない技術や考え方もアップしていますので、
よければフォローして頂けると嬉しいです。
詳しくはこちら https://twitter.com/japwork

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