我已在现有应用程序中安装了 Devise,并且需要为数据库提供 100 个用户的种子。他们现在拥有 Devise 添加的字段,例如电子邮件和加密密码等。我正在尝试的种子文件部分是这样的: (种子.rb...)
users = [] # Empty array to store users
100.times do
username = "#{Faker::Vehicle.make}#{Faker::BaconIpsum.word}-#{rand(999)}"
user_password = SecureRandom.base64(12)
u = User.new
u.id = SecureRandom.random_number(9999999999)
u.username = username.gsub(/\s+/,"")
u.password = user_password
u.password_confirmation = user_password
u.email = "#{Faker::Internet.free_email}"
u.sign_in_count = 0
u.save
users << u # Put newly created user in the array
end
仅使用 NOT NULL 字段进行播种。当我尝试播种时,出现以下错误:
block 引用>ActiveRecord::StatementInvalid: Mysql2::Error: Field 'password' doesn't have a default value: INSERT INTO
users
(encrypted_password
,id
,username
) VALUES ('colton@gmail.com', '$2a$10$F9RR6h3R48ySJ3./lrPgfeqE84MgPJh7TVseXL.ngwU1Xp5hYxPDC', 3494734525, 'Mitsubishibrisket-872')编辑:用户表的 schema.rb,由迁移生成...
create_table "users", force: true do |t| t.string "username", limit: 30, null: false t.string "password", limit: 30, null: false 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" end add_index "users", ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true, using: :btree add_index "users", ["username", "id"], name: "BY_USERNAME", using: :btree
显然,我在这里传递了“密码”的值。在SO等其他帖子之后,我学会了发送“密码”和“密码确认”,而不是尝试发送“加密密码”。仍然得到同样的错误。为什么这不起作用? 我应该在 seeds.rb 文件中要求“devise”吗? 阅读错误,似乎我应该更改“密码”字段以允许 NULL 并只存储“加密”密码。
请帮忙,谢谢!
最佳答案
我修好了。我所做的就是删除数据库并进入创建用户表的迁移文件。 不是“add_devise_to_users”迁移,而是原始迁移。这是密码字段所在的位置。更改为添加默认值。现在看起来像这样...
class CreateUsers < ActiveRecord::Migration
def self.up
# create USERS table
create_table "users", id: false, force: true do |t|
t.integer "id", limit: 8, default: 0, null: false
t.string "username", limit: 30, default: "", null: false
t.string "password", limit: 30, default: "", null: false
end
execute "ALTER TABLE users ADD PRIMARY KEY (id);"
add_index "users", ["username", "id"], name: "BY_USERNAME", using: :btree
end
def self.down
drop_table :users
end
end
如您所见,我还为“id”字段添加了默认值,因为显然 Devise 存在问题。更改此设置后,运行 rake db:create、rake db:migrate 和 rake db:seed。
这解决了我的问题,我可以使用 seeds.rb 创建用户和种子。乍一看,为密码和用户 ID 提供默认值似乎是一件不安全的事情。但如果它被验证为“唯一性”,我想这是可以的。
欢迎评论
关于mysql - Rails 4 设计具有随 secret 码的种子用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28786432/