我已在现有应用中安装了Devise,需要为100个用户播放数据库。他们现在拥有Devise添加的字段,例如email和encrypted_password等。我尝试的种子文件的部分是: (seeds.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字段播种。当我尝试播种时,我收到以下错误:
ActiveRecord :: StatementInvalid:Mysql2 :: Error:Field&#39; password&#39;没有默认值:INSERT INTO
users
(encrypted_password
,id
,username
)VALUES(&#39; colton @ gmail.com&#39;,&#39; $ 2a $ 10 $ F9RR6h3R48ySJ3。/ lrPgfeqE84MgPJh7TVseXL.ngwU1Xp5hYxPDC&#39;,3494734525,&#39; Mitsubishibrisket-872&#39;)
编辑:用户表格的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
显然,我为&#34;密码&#34;传递了一个值。这里。在关于SO等的其他帖子之后,我学会了发送&#34;密码&#34;和&#34; password_confirmation&#34;而不是试图发送&#34; encrypted_password&#34;。仍然得到相同的错误。为什么这不起作用? 我是否应该要求设计&#39;在我的seeds.rb文件中? 阅读错误,我似乎应该改变密码&#34;字段允许NULL并且只是存储&#34;加密&#34;密码。
请帮助,谢谢!
答案 0 :(得分:0)
我修好了。我做的是删除数据库并进入我创建Users表的迁移文件。 不“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提供默认值。但是,如果它被验证为“唯一性”,我想这没关系。
欢迎评论