Question

In my User model I set validations for the password and its confirmation:

validates_presence_of :password, :password_confirmation

I use this for the forms. These attributes are not stored in the database, I am using the authlogic gem.

Now I am trying to make a system to restore forgotten passwords via email. The user inputs his email and the object is retrieved like this:

@user = User.find_by_email(params[:email])

Then, at a certain point in the process the value of a User attribute is set to true meaning that the user forgot his password, so I need to do a @user.save.

And there's the problem. Since password and password_confirmation were never stored, their values are nil. However, the validations come in play and prevent the user from being updated.

Is there any way to skip those particular validations so I can make this work? Or should I do something else? Any help?

Was it helpful?

Solution

You can skip all validations with save(validate: false). You can skip individual validations with the :if or :unless option, for example.

validates_presence_of :password, :password_confirmation, unless: :forgot_password?

def forgot_password?
  # return true if the user is in the forgot password process
end

OTHER TIPS

change

validates_presence_of :password, :password_confirmation

to

Assuming your field that is set to true is forgot_password

validates_presence_of :password, :password_confirmation, :unless =>  Proc.new { |a| a.forgot_password? }

Conditional Validations documentation

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top