"Password can't be blank" 播种数据库时出错

"Password can't be blank" error when seeding database

我正在尝试使用通过 seed_dump gem、found here. 获取的数据为我的数据库做种与用户模型验证发生冲突:

ActiveRecord::RecordInvalid: Validation failed: Password can't be blank

给出一个想法,种子看起来像这样:

User.create!([
  {email: "1234@localhost", encrypted_password: "aeoHh6M2q4GjGkHClO.NqebWWhS94D8rNj5Ot6CB2qrbn7IrTfkSa", reset_password_token: nil, reset_password_sent_at: nil, remember_created_at: nil, sign_in_count: 1, current_sign_in_at: "2014-12-31 22:27:09", last_sign_in_at: "2014-12-31 22:27:09", current_sign_in_ip: "127.0.0.1", last_sign_in_ip: "127.0.0.1", admin: false}
])

此外,我正在为用户使用 devise gem management。

在给定此过滤器的情况下,是否有一种优雅的方式来播种用户数据?

你可以这样做:

u = User.new([
  {email: "1234@localhost", encrypted_password: "aeoHh6M2q4GjGkHClO.NqebWWhS94D8rNj5Ot6CB2qrbn7IrTfkSa", reset_password_token: nil, reset_password_sent_at: nil, remember_created_at: nil, sign_in_count: 1, current_sign_in_at: "2014-12-31 22:27:09", last_sign_in_at: "2014-12-31 22:27:09", current_sign_in_ip: "127.0.0.1", last_sign_in_ip: "127.0.0.1", admin: false}
])
u.save!(validate: false)

有同样的问题。 User.new 解决方案 对我有用。

以下解决方案确实有效,来自 "Seeding Users with Devise" 上的类似问题: Seeding users with Devise in Ruby on Rails

简而言之,encrypted_password替换为密码纯文本 您习惯使用的密码。

示例:

User.create!([
  {email: "1234@localhost", password: "some_password", reset_password_token: nil, reset_password_sent_at: nil, remember_created_at: nil, sign_in_count: 1, current_sign_in_at: "2014-12-31 22:27:09", last_sign_in_at: "2014-12-31 22:27:09", current_sign_in_ip: "127.0.0.1", last_sign_in_ip: "127.0.0.1", admin: false}
])

然后您可以 运行 rake db:seed。 Rails 将为每个用户施展魔法(通过自动创建 encrypted_password 哈希),您将能够正常登录。