neanderslob
neanderslob

Reputation: 2693

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

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?

Upvotes: 3

Views: 4246

Answers (2)

Kobi
Kobi

Reputation: 4243

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.

Upvotes: 2

BroiSatse
BroiSatse

Reputation: 44685

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)

Upvotes: 3

Related Questions