“Password can't be blank” error when seeding database

自作多情 提交于 2019-12-24 12:03:56

问题


I'm attempting to seed my database using the data that I grabbed with the seed_dump gem, found here. Anyway, the seed file generated looks legit, but it seems to be falling afoul of the user model validation:

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

To give an idea the seed looks like this:

User.create!([
  {email: "1234@localhost", encrypted_password: "$2a$10$5eoHh6M2q4GjGkHClO.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}
])

Also, I'm using the devise gem for users management.

Is there an elegant way to seed the user data given this filter?


回答1:


You can do:

u = User.new([
  {email: "1234@localhost", encrypted_password: "$2a$10$5eoHh6M2q4GjGkHClO.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)



回答2:


Had the same issue. The User.new solution did not work for me.

The following solution did work, from similar question on "Seeding Users with Devise" here: Seeding users with Devise in Ruby on Rails

In short, replace the encrypted_password with password and a plain text password you are comfortable using.

Example:

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}
])

You can then run rake db:seed. Rails will do its magic (by automatically creating the encrypted_password hash) for each user, and you will be able to login normally.



来源:https://stackoverflow.com/questions/27931101/password-cant-be-blank-error-when-seeding-database

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!