gpt4 book ai didi

ruby-on-rails - rake db :seed 验证失败

转载 作者:数据小太阳 更新时间:2023-10-29 07:16:50 25 4
gpt4 key购买 nike

我正在学习 hartle 教程的第 12 章。当我运行 bundle exec rake db:seed 时,我得到了这个错误:

ActiveRecord::RecordInvalid: Validation failed: Email has already been taken

我试着运行

rake db:reset
rake db:migrate
rake db:test:prepare

最后

rake db:populate 

但他们并没有解决问题。当我运行 rake db:populate 它给出:

Don't know how to build task 'db:populate'

这是我的 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) }

我想问题可能出在这一行 email = "example-#{n+1}@railstutorial.org"

最佳答案

你的问题是 rake db:reset 不仅删除并重新创建数据库,而且 it also migrates and seeds it as well .所以基本上发生的事情是这样的:

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)

然后你运行:

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)

很明显,如果你停止运行 rake db:prepare 命令,你的问题就会消失。然而,为了避免将来发生这些事情,我强烈建议在你的种子文件中加入一些逻辑。它只是 Ruby,因此您可以将 User 创建的内容包装在 unless 语句中,例如:

unless User.find_by( email: "example@railstutorial.org" )
# create all 100 users
end

如果您的生产站点仍在使用种子数据(例如 SiteSetting 表),这将证明特别有值(value);您需要确保数据进入您的生产数据库,但您将创建重复的记录(或错误)再次运行种子而不丢失。

作为您问题答案的附加引用,请参阅 this one 的选定答案。 .

我希望这提供了您需要的所有信息!

关于ruby-on-rails - rake db :seed 验证失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29986540/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com