编辑真正愚蠢的错误:
数据库:重置种子数据库。
我试图建立一个数据库,创建有帖子的用户,但这些用户不断违反唯一性约束。。。即使只有一个。
目前,我还没有模型验证。
标准的用户设计模式:
create_table "users", force: :cascade do |t|
t.string "email", default: "", null: false
t.string "encrypted_password", default: "", null: false
t.string "reset_password_token"
t.datetime "reset_password_sent_at"
t.datetime "remember_created_at"
t.integer "sign_in_count", default: 0, null: false
t.datetime "current_sign_in_at"
t.datetime "last_sign_in_at"
t.string "current_sign_in_ip"
t.string "last_sign_in_ip"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "username"
end
add_index "users", ["email"], name: "index_users_on_email", unique: true
add_index "users", ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true
db/seeds.rb
1.times do |n|
email = Faker::Internet.email
username = Faker::Name.name
password = 'password'
password_confirmation = 'password'
reset_password_token = nil
id = n
User.create!(
email: email,
username: username,
password: password,
password_confirmation: password_confirmation,
reset_password_token: reset_password_token,
id: id
)
end
我运行了以下程序:
rails c
rake db:reset
rake db:migrate
rake db:seed
>> ActiveRecord::RecordNotUnique: SQLite3::ConstraintException: UNIQUE constraint failed: users.id: INSERT INTO "users"
我只有一个生成的用户,但违反了唯一性。堆栈跟踪告诉我create方法有问题,但我不知道如何解决这个问题。
我只有两种可能的东西需要在数据库级别上是唯一的,那就是index_users_on_email和index_users_on_reset_password,如果数据库被重置并只植入一条记录,这两种东西都是唯一的。
我哪里错了?
以下是我为用户创建种子的方式,希望能有所帮助。
1.times do
user = User.new(
name: Faker::Name.name,
email: Faker::Internet.email,
password: Faker::Lorem.characters(10)
)
user.skip_confirmation!
user.save!
end
users = User.all