I will output what I learned by studying seed! I hope it will be helpful for those who are learning seed from now on.
The seed file is the initial data. For example, if you reset the database during development, all the data will be lost. If it disappears every time, if there is a registration function, it will be necessary to re-register the data every time it is reset. It's really troublesome, isn't it? Therefore, if you describe the data you want to put in the seed file in db / seeds.rb, you do not have to recreate it one by one! !! !!
This will create one seed data for User.
User.create!(email: "[email protected]",password: "password" )
It uses basic Ruby commands! I'm passing n as an argument so that the emails aren't the same. The reason for setting it to n + 1 is that if it is only n, the data will start from 0.
10.times do |n|
User.create!(
email: "user#{n+1}@example.com",
password: "password" )
end
For example, suppose you have a User and its associated Task model. As seed data, we will generate a Task related to the User model. Then you can write as below!
User.all.each do |user|
Task.create!(
user_id: user.id,
title: "title",
memo: "memo",
color: "red",
start_date: "2020/5/1",
end_date: "2020/5/30" )
end
To read the CSV file, write as follows. The "db / csv / masters / init_categories.csv" part changes depending on where you put the file.
CSV.foreach("db/csv/masters/init_categories.csv") do |row|
@categories = Masters::Category.create!(name: row[0])
end
This time, I prepared a sample image under the application, so I will describe how to do it below. Load using the open method.
User.create!(
image: open("db/images/sample.png "),
title: "topic",
overview: "Overview",
link: "http://origin_job_topic_sample.com" )
For example, when the User model is described as below, when creating seed data, you want a pattern that contains both, right? By the way, enum is a function that allows you to store users and admins numerically.
enum user_type: {
user: 0,
admin: 1,
}
In such a case, if you write as follows, the data will be created randomly! This also uses the basic writing style of Ruby!
User.create!(
email: "[email protected]",
password: "password",
status: rand(0..1) )
I hadn't touched seed before I changed jobs, but I think I learned the basics this time. I'm still learning, so I'll update it as soon as I get new knowledge! !!
Recommended Posts