$ rails db:seed
-----user start-----
count from: 0
count to: 10
3.4542s
-----user end-----
-----post start-----
count from: 0
count to: 13
0.1095s
-----post end-----
3.5883s
First of all, as with the modification of controller, post is generated from user, so we will create it from user_seeds.rb.
db/seeds/user_seeds.rb
# frozen_string_literal: true
unless User.exists?
10.times do |i|
email = "test#{i + 1}@example.com"
User.create!(email: email, password: "password",
uid: email, provider: "email", name: Faker::Name.name)
end
end
For the time being, let's generate 10 almost users.
Next, generate post_seeds.rb so that it belongs to the user created above.
db/seeds/post_seeds.rb
# frozen_string_literal: true
unless Post.exists?
users = User.all
users.each do |user|
Random.rand(0..3).times do
user.posts.create!(subject: Faker::Lorem.word, body: Faker::Lorem.paragraph)
end
end
end
Get all users and randomly generate 0 to 3 posts.
It's a good idea to remember Random.rand (x..x)
as it is a technique often used in seed.
db/seeds.rb
# frozen_string_literal: true
seed_models = %i[user post]
all_process_time = Benchmark.realtime do
seed_models.each do |model|
puts "-----#{model} start-----"
puts "count from: #{model.to_s.classify.constantize.count}"
process_time = Benchmark.realtime do
require "./db/seeds/#{model}_seeds"
end
puts "count to: #{model.to_s.classify.constantize.count}"
puts "#{format('%.4<time>f', time: process_time)}s"
puts "-----#{model} end-----"
end
end
puts "#{format('%.4<time>f', time: all_process_time)}s"
$ rails db:seed
-----user start-----
count from: 0
count to: 10
3.4542s
-----user end-----
-----post start-----
count from: 0
count to: 13
0.1095s
-----post end-----
3.5883s
As the number of models increases and the processing time increases, it should be easier to investigate where the bottleneck is.
→ Building a bulletin board API with authentication authorization with Rails 6 # 15 pundit introduction [To the serial table of contents]