[Ruby] Create a large number of records with one command using the Ruby on Rails seeds.rb file

less than 1 minute read

What is # seeds.rb? A file in the app/db directory used to create records.

Even if you do not manually register each data when creating a record, You can use seeds.rb to create a large number of records with one command. How to create a record using # seeds.rb

  1. Describe the record creation process in the seeds.rb file
  2. Run rails db:seed
  3. Processing of seeds.rb file is executed

Example: Register 100 names and email addresses in the users table

Write the following in app/db/seeds.rb,

seeds.rb


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

When I run rails db:seed, The users table has name and email values

“name0, [email protected]”, “name1, [email protected]”, ・ ・ ・ “name99, [email protected]

100 records are registered as shown in.