3

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?

neanderslob
  • 2,633
  • 6
  • 40
  • 82
  • 1
    why won't you just change encrypted_password to password to pass the validation? – Andrey Deineko Jan 13 '15 at 20:44
  • @AndreyDeineko Thanks for the response. Very fair question; I was actually about to give that a shot. This was more a question to see if there's an elegant way to avoid this sort of validation when seeding. – neanderslob Jan 13 '15 at 20:47

2 Answers2

3

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)
BroiSatse
  • 44,031
  • 8
  • 61
  • 86
  • The syntax may have changed in Rails 6. I got an error: "ArgumentError: When assigning attributes, you must pass a hash as an argument, Array passed," when I followed this example. I removed the array brackets, so instead it was just: `u = User.new({{email: "1234@localhost", encrypted_password: "..."})`, and that worked. – antun Jun 01 '20 at 01:58
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.

Community
  • 1
  • 1
Kobi
  • 4,003
  • 4
  • 18
  • 23