Whenever test data is needed during development, it is troublesome to hit rails c
or create action to create a record.
Therefore, we will introduce a seed that makes it easy to create a preset record, 50 or 1000, just by hitting a command.
If you google only rails seed, it will usually be written directly in db / seeds.rb, but if there are many models, it will be difficult to manage. Therefore, divide the file and make it a format called by require from db / seeds.rb.
This makes it easier to manage when adding or deleting, and seed can also be executed by specifying a file, which is convenient.
$ mkdir db/seeds
$ touch db/seeds/post_seeds.rb
db/seeds.rb
# frozen_string_literal: true
seed_models = %i[post]
seed_models.each do |model|
require "./db/seeds/#{model}_seeds"
end
db/seeds/post_seeds.rb
# frozen_string_literal: true
unless Post.exists?
20.times do
Post.create!(subject: "hoge", body: "fuga")
end
end
Expecting that the number of models to be seeded will increase in the future, we will read the external file by adding it to the variable called seed_models. By scanning the directory, you can make it so that you do not have to change db / seeds.rb each time, but there will be dependencies such as the user model record to be created in the future must exist before the post model. So, I wrote it so that I can manually play with the execution order.
The contents of post_seeds.rb are simply running Post.create!
20 times.
By adding !
, An exception will be thrown when registration cannot be performed due to a validation error, so if you notice it, you can prevent the situation where the record was not generated.
$ rails db:reset
$ rails db:seed
$ rails c
[1] pry(main)> Post.count
(1.1ms) SELECT COUNT(*) FROM "posts"
=> 20
By resetting db: reset, all the tables are dropped and regenerated. This will execute a seed that works only when there is a record. And by db: seed, you can see that 20 records have been added.
It's nice to have a record, but the subject is hoge and the body is fuga. At this rate, if you get it from the API for some reason, it will be difficult to notice even if the same record is confused. However, it is troublesome to create a completely random character string each time, so Faker is useful.
Let's put it in for the time being.
Gemfile
...
group :development, :test do
...
+ "faker"
end
...
$ bundle
Let's try it out.
$ rails c
[1] pry(main)> Faker::Name.unique.name
=> "Miss Porter Kovacek"
[2] pry(main)> Faker::Name.name
=> "Felicita Durgan"
[3] pry(main)> Faker::Name.name
=> "Yong Weissnat"
[4] pry(main)> Faker::Name.name
=> "Sandie Oberbrunner"
Like this, it automatically returns random nouns and sentences each time it is executed. The words defined by default should be Check on Github. Not only people's names, animals, addresses and phone numbers, but also movies, manga, games, dramas, music. There are even Pokemon names and the Devil Fruit of ONE PIECE.
db/seeds/post_seeds.rb
# frozen_string_literal: true
unless Post.exists?
20.times do
- Post.create!(subject: "hoge", body: "fuga")
+ Post.create!(subject: Faker::Lorem.word, body: Faker::Lorem.paragraph)
end
end
$ db:reset
$ db:seed
$ rails c
[1] pry(main)> Post.all
Post Load (0.4ms) SELECT "posts".* FROM "posts"
=> [#<Post:0x000000000636cbe8
id: 1,
subject: "quos",
body: "Earum numquam qui. Impedit autem molestias. Ipsum adipisci eos.",
created_at: Sun, 06 Sep 2020 15:36:27 UTC +00:00,
updated_at: Sun, 06 Sep 2020 15:36:27 UTC +00:00>,
#<Post:0x00000000063b5be0
id: 2,
subject: "vero",
body:
"Impedit distinctio saepe. Adipisci cupiditate officiis. Vel et deleniti.",
created_at: Sun, 06 Sep 2020 15:36:27 UTC +00:00,
updated_at: Sun, 06 Sep 2020 15:36:27 UTC +00:00>,
You can see that the records of random subject and body are created.
It is inconvenient to create a Japanese site if it is in English even though you put it in, so let's localize it. Since db: seed is executed in the dev environment, let's try to Japaneseize Faker in the dev environment.
config/environments/development.rb
Rails.application.configure do
...
+ Faker::Config.locale = "ja"
end
If you don't like Japaneseization all the time, you can put Faker :: Config.locale =" ja "
in db / seeds / post_seeds.rb.
Then run seed again.
$ rails db:reset
$ rails db:seed
$ rails c
[1] pry(main)> Post.all
Post Load (0.3ms) SELECT "posts".* FROM "posts"
=> [#<Post:0x0000000006480b88
id: 1,
subject: "Go",
body: "Captain General Police Officer. Meishibokin Katamichi. Traditional Tokugawa super ~.",
created_at: Sun, 06 Sep 2020 15:45:27 UTC +00:00,
updated_at: Sun, 06 Sep 2020 15:45:27 UTC +00:00>,
#<Post:0x00000000064fb928
id: 2,
subject: "French",
body: "~ System last week. I'm going home. High price at the store.",
created_at: Sun, 06 Sep 2020 15:45:27 UTC +00:00,
updated_at: Sun, 06 Sep 2020 15:45:27 UTC +00:00>,
It has been successfully translated into Japanese. In addition, you can Check on Github if it is translated into Japanese. Conversely, what is not in this is still in English.
→ Introduction of # 9 serializer to build bulletin board API with authentication authorization in Rails 6 [To the serial table of contents]