我想用多个商店和用户填充数据库,每个用户对应一个商店。以下代码的问题是我收到错误验证失败:已经收到电子邮件。
namespace :db do
desc "Fill database with sample data"
task populate: :environment do
make_stores
make_users
end
end
def make_stores
50.times do
name = Faker::Company.name
manager = Faker::Name.name
address = Faker::Address.street_name
Store.create!(name: name,
manager: manager,
address: address)
end
end
def make_users
stores = Store.all(limit: 8)
99.times do |n|
first_name = Faker::Name.first_name
last_name = Faker::Name.last_name
email = "example-#{n+1}@example.org"
password = "password"
stores.each { |store| store.users.create!(first_name: first_name,
last_name: last_name,
email: email,
password: password,
password_confirmation: password) }
end
end
答案 0 :(得分:1)
问题是您在调用stores.each
之前设置了电子邮件变量,因此所有8个商店都会让用户使用相同的电子邮件。
做这样的事情:
def make_users
stores = Store.all(limit: 8)
99.times do |n|
password = "password"
stores.each do |store|
first_name = Faker::Name.first_name
last_name = Faker::Name.last_name
email = "#{store.name.parameterize}-#{n+1}@example.org"
store.users.create!(first_name: first_name,
last_name: last_name,
email: email,
password: password,
password_confirmation: password)
end
end
end
现在前8位用户将收到(some-store-name)-1@example.org
这样的电子邮件,接下来会有8位(some-store-name)-2@example.org
,依此类推。