LoginSignup
0
0

More than 1 year has passed since last update.

【Rails】サンプルユーザーを増やす!Fakerの導入でサクラを作る方法

Posted at

対象者

  • 作成したサイトにテストユーザーを大量に導入したい方

目的

  • Gem「Faker」を使用してデータを増やすこと

実際の手順と実例

1.Fakerとは

Fakerとは実際にいそうなユーザー名(ユーザー以外も行ける??)を作成するGemです。

これの導入によって手作業で1人ずつユーザー登録をしていくという作業や手間をカットできます。

2.Faker導入方法

1.gemに導入
:
:
gem 'rails',                   '6.0.3'
gem 'bcrypt',                  '3.1.13'
gem 'faker',                   '2.1.2'
gem 'will_paginate',           '3.1.8'
:

この後bundle installを実行します

2.サンプルユーザー作成

seedファイルに作成していきます。

まずメインとなるユーザーを1人作成します

db/seed.rb
User.create!(name:  "Example User",
             email: "example@railstutorial.org",
             password:              "foobar",
             password_confirmation: "foobar")

続いて、追加で偽物を何人作成するのか決めていきます。

db/seed.rb
#上記と同じ
User.create!(name:  "Example User",
             email: "example@gmail.com",
             password:              "foobar",
             password_confirmation: "foobar")

#ここから追記
99.times do |n|
  name  = Faker::Name.name
  email = "example-#{n+1}@gmail.com"
  password = "password"
  User.create!(name:  name,
               email: email,
               password:              password,
               password_confirmation: password)
end

これで完了です。ここでは99人のユーザーを作成しました。
この後、rails db:seedを実行すれば完了です。

⚠先に何かデータが入っていいる場合、rails db:migrate:resetするといいかもしれません!また、サーバー起動中はrails db:migrate:resetがうまくできないこともあるそうなので、再起動して実行がおすすめです!

参照

Rails tutorial 10.3.2サンプルのユーザー

投稿者コメント

Rails tutolialを進めてたら何やら面白そうなGemがあるなあとおもって記事にしました。
これからPF作成もあるので、使ってみようかなと思っています!

My Profile

プログラミング学習歴3ヶ月目のアカウントです!
プログラミングスクールで学んだ内容や自分が躓いた箇所等のアウトプットの為に発信しています。
また、プログラミング初学者の方にわかりやすく、簡潔にまとめて情報共有できればと考えています。
もし、投稿した記事の中に誤り等ございましたら、コメント欄でご教授いただけると幸いです。 

0
0
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
0
0