Han*_*nna 5 ruby ruby-on-rails railstutorial.org
我正在做hartle教程的第12章.我跑的时候遇到bundle exec rake db:seed了这个错误:
ActiveRecord::RecordInvalid: Validation failed: Email has already been taken
Run Code Online (Sandbox Code Playgroud)
我试着跑步
rake db:reset
rake db:migrate
rake db:test:prepare
Run Code Online (Sandbox Code Playgroud)
最后
rake db:populate
Run Code Online (Sandbox Code Playgroud)
但他们没有解决问题.当我运行rake db:populate它时给出:
Don't know how to build task 'db:populate'
Run Code Online (Sandbox Code Playgroud)
这是我的seeds.rb文件:
# Users
User.create!(name: "Example User",
email: "example@railstutorial.org",
password: "foobar",
password_confirmation: "foobar",
admin: true,
activated: true,
activated_at: Time.zone.now)
99.times do |n|
name = Faker::Name.name
email = "example-#{n+1}@railstutorial.org"
password = "password"
User.create!(name: name,
email: email,
password: password,
password_confirmation: password,
activated: true,
activated_at: Time.zone.now)
end
# Microposts
users = User.order(:created_at).take(6)
50.times do
content = Faker::Lorem.sentence(5)
users.each { |user| user.microposts.create!(content: content) }
end
# Following relationships
users = User.all
user = users.first
following = users[2..50]
followers = users[3..40]
following.each { |followed| user.follow(followed) }
followers.each { |follower| follower.follow(user) }
Run Code Online (Sandbox Code Playgroud)
我想也许问题出在这条线上 email = "example-#{n+1}@railstutorial.org"
你的问题是rake db:reset不仅会丢弃并重新创建数据库,而且它也会迁移并播种它.基本上发生的事情是这样的:
rake db:drop
rake db:create
rake db:schema:load # (think of this as running all the migrations you've run before)
rake db:seed # (creates your 100 database users)
Run Code Online (Sandbox Code Playgroud)
然后你运行:
rake db:migrate # (likely unnecessary, but it causes no harm)
rake db:test:prepare # (prepares the test database)
rake db:prepare # (runs the seeds AGAIN and causes your errors)
Run Code Online (Sandbox Code Playgroud)
显然,如果你只是停止运行rake db:prepare命令,你的问题就会消失.但是,为了避免将来出现这些问题,我强烈建议在种子文件中加入一些逻辑.它只是Ruby,因此您可以将用户创建包装在unless语句中,例如:
unless User.find_by( email: "example@railstutorial.org" )
# create all 100 users
end
Run Code Online (Sandbox Code Playgroud)
如果您的生产站点仍然使用种子数据(例如SiteSetting表),这将证明特别有价值; 您需要确保数据进入生产数据库,但是您将创建重复运行种子的重复记录(或错误)而不会丢失.
至于回答你的问题的附加参考,请选择答案,这一个.
我希望这能提供您需要的所有信息!