Search code examples
ruby-on-railscallbackbcryptpassword-encryptionchange-password

trying to assign passwords where empty but overriding users passwords. My fix gets invalid Hash error


I'm sure this may be something obvious but I'm quite new to Bcrypt and am trying to build an app where I am uploading many users whose emails I have but no passwords - I want to assign random passwords to users so that they can click on 'forgot password' to set a new password. However my method for setting the random password is overwriting the new password when saving. The fixes I have found on here are giving me an 'Invalid Hash' error. Any help much appreciated. Code below:

User model:

class User < ActiveRecord::Base
attr_accessor :remember_token, :activation_token, :reset_token, :user_params
before_save   :downcase_email, :downcase_role
after_save :set_password_if_nil  
before_create :create_activation_digest

Solution

  • When you are uploading the users means you are creating some new records so instead of after_save which runs on both create and update you can use after_create. So this will run only on creating the new records. Hope this helps.