1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Rails 6で認証認可入り掲示板APIを構築する #14 seed実行時間の表示

Last updated at Posted at 2020-09-19

Rails 6で認証認可入り掲示板APIを構築する #13 認証ヘッダの付与

完成図

$ 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

seedsファイルの編集

まずはcontrollerの修正と同じく、postはuserから生成するため、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

とりあえず10ほぼユーザーを生成してみましょう。

続いて、post_seeds.rbを上記で生成したユーザーに所属させる形で生成します。

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

全ユーザーを取得し、0から3件ランダムで投稿を生成します。
Random.rand(x..x)はseedでよく使う手法なので覚えておくと良いです。

db/seeds.rbの編集

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

modelが増えてきて処理時間が伸びてきたら、どこがボトルネックになっているのか調査しやすくなるはずです。

続き

Rails 6で認証認可入り掲示板APIを構築する #15 pundit導入
連載目次へ

1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?