LoginSignup
15
23

More than 5 years have passed since last update.

seedデータの投入方法

Posted at

seedデータとは?

railsアプリを作成する際にあらかじめ適当なデータを投入する。このデータベース初期化用のデータをseedデータと呼ぶ。

投入方法

1.dbフォルダのseeds.rbにseedデータを投入するスクリプトを記載する。

db/seeds.rb
Post.create(title: "seedデータについて", body: "seedデータとはダミーデータのことである", category: "プログラミング")

今回はPostモデルに、

* title
* body
* category

の3つのカラムを作成している。

2.ターミナルの操作

$ rake db:seed

これでデータベースに反映される
しかしこれでは1件しかデータが投入できない。この記法で100件分のデータを投入するには100回Post.create()と記載する必要がある。一気にデータを投入したい時には以下の記法を用いる。

db/seeds.rb
100.times do |index|
  Post.create(title: "タイトル#{index}", body: "ブログの内容#{index}", category: "カテゴリー#{index}")
end

kobito.1451459348.177148.png

Rubyのtimesメソッドを用いて100件分のデータを登録できる。

15
23
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
15
23