0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Ruby on Rails seeds.rbファイルを使って、コマンド1つでレコードを大量作成

Posted at

seeds.rbとは?

app/db ディレクトリにあるファイルで、レコードの作成に使うファイル。

レコードを作成する際に手作業で1つ1つデータを登録しなくても、
seeds.rbを使用すると大量のレコードをコマンド1つで作成することができる。

seeds.rbを使用したレコード作成方法

  1. seeds.rb ファイルにレコード作成の処理を記述
  2. rails db:seed を実行
  3. seeds.rb ファイルの処理が実行される

例:usersテーブルに100人分の名前とメールアドレスを登録

app/db/seeds.rb に以下のように記述し、

seeds.rb
100.times do |n|
  User.create(name: "name#{n}", email: "mail#{n}@gmail.com")
end

rails db:seed を実行すると、
users テーブルには name, email の値がそれぞれ

"name0, mail0@gmail.com",
"name1, mail1@gmail.com",



"name99, mail99@gmail.com"

のようにレコードが100件登録される。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?