2
0

More than 3 years have passed since last update.

リレーションシップのダミーデータを作成する

Posted at

環境

ruby '2.6.5'
rails '6.0.3'

seeds.rb

# user
User.create(
  email:                'aaaaaa@au.com',
  password:             'aaaaaa',
  account:              'arigatou'
  )

5.times do
email = Faker::Lorem.sentence(word_count: 8) + '@au.com'
password = 'password'
account = Faker::Lorem.sentence(word_count: 6)
User.create!(
      email:                 email,
      password:              password,
      account:               account
      )
end

# article
users = User.all
5.times do
content = Faker::Lorem.sentence(word_count: 50)
users.each { |user| user.articles.create!(content: content) }
end

#relationship
users = User.all
user = users.first
following = users[1..6]
followers = users[1..6]
following.each { |followed| user.follow!(followed) }
followers.each { |follower| follower.follow!(user) }

コード説明

以下の記述でログインする用のユーザーを作成

# user
User.create(
  email:                'aaaaaa@au.com',
  password:             'aaaaaa',
  account:              'arigatou'
  )

以下の記述で
5人のユーザーを作成します。
今回はemailとaccountカラムは一意に設定しているのでfakerでランダムに作成します。
バリデーションなどで文字数の指定をしている場合はバリデーションに合わせた数字に変更してください


5.times do
email = Faker::Lorem.sentence(word_count: 8) + '@au.com'
password = 'password'
account = Faker::Lorem.sentence(word_count: 6)
User.create!(
      email:                 email,
      password:              password,
      account:               account
      )
end

以下のコードは
作成したユーザー全てにarticleを作成させたいので
全てのuserを取得し、ランダムな文字列のcontentを作り、
each文でarticleを作成するという流れになります

# article
users = User.all
5.times do
content = Faker::Lorem.sentence(word_count: 50)
users.each { |user| user.articles.create!(content: content) }
end

最後にフォロー関係ですが
全てのユーザーを取得、
最初のユーザーをログインするユーザーと仮定し取得し、
それ以外のユーザーをフォロー、また他のユーザーにフォローされるという状況を作りたいので
following = users[1..6]
followers = users[1..6]
という記述になります
取得したユーザーをあとはeachでフォローしていく、してもらうという記述になります
なのでrails db:seedを行ったあとのリレーションは
user.firstは6人のユーザーにフォローされていて
user.firstは自分以外の6人にフォロされている状態になる

#relastionship
users = User.all
user = users.first
following = users[1..6]
followers = users[1..6]
following.each { |followed| user.follow!(followed) }
followers.each { |follower| follower.follow!(user) }
2
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
2
0