[Ruby] [Rails] How to make seed

2 minute read


We will study seed and output what we have learned! I hope that it will be helpful to those who are learning seed from now on.

What is #seed The seed file is the initial data. ―― For example, if you reset the database during development, all the data will be lost. If there is a registration function that disappears every time, you will have to re-register the data each time you reset. ―― It’s very troublesome, right? ‥ Therefore, if you describe the data you want to put in the seed file in db/seeds.rb, you will not have to recreate it each time! !! !!

Basic pattern

This will create one User seed data.

User.create!(email: "[email protected]",password: "password")

When you want to create multiple seed data

This uses basic Ruby commands! n is passed as an argument so that the emails will not be the same. The reason for setting n+1 is that the data will start from 0 if only n is set.

10.times do |n|
   email: "user#{n+1}@example.com",
   password: "password")

About creating data for association

For example, suppose you have a User and a Task model associated with it. As seed data, we will generate a Task related to the User model. Then you can write as below!

User.all.each do |user|
  user_id: user.id,
  title: "title",
  memo: "memo",
  color: "red",
  start_date: "2020/5/1",
  end_date: "2020/5/30")

How to read CSV file

To read the CSV file, enter as follows. The “db/csv/masters/init_categories.csv” part changes depending on where you put the files.

CSV.foreach("db/csv/masters/init_categories.csv") do |row|
 @categories = Masters::Category.create!(name: row[0])

About inserting images

This time I prepared a sample image under the application, so I will describe the method below. Load it using the open method.

    image: open("db/images/sample.png"),
    title: "Topic",
    overview: "Overview",
    link: "http://origin_job_topic_sample.com")

When you want to enter values randomly

For example, when the User model has the following description, when you create seed data, you want a pattern that contains both, right? By the way, enum is a function that allows users and admins to be stored numerically.

enum user_type: {
    user: 0,
    admin: 1,

In such a case, write like the one below and it will create data randomly! This also uses the basic Ruby syntax!

 email: "[email protected]",
 password: "password",
 status: rand(0..1))


I hadn’t touched seed before changing jobs, but I think I could learn the basics this time. I’m still learning, so I’ll update it whenever I get new knowledge! !!