An odd thing occurs when attempting to resave a User after pulling it from the database. Validation on password fails:
Why
This peculiarity happens because has_secure_password actually does the validation and presence checks for password when it automatically generates the value for password_digest. However, after the password_digest is present, the password field is set to nil. As a result, any custom validations added on the model for password will fail after that point since password is set to nil. So in our case, it is ok to have a nil password after creation.
Problem
An odd thing occurs when attempting to resave a
User
after pulling it from the database. Validation onpassword
fails:Why
This peculiarity happens because
has_secure_password
actually does the validation and presence checks forpassword
when it automatically generates the value forpassword_digest
. However, after thepassword_digest
is present, thepassword
field is set tonil
. As a result, any custom validations added on the model forpassword
will fail after that point sincepassword
is set tonil
. So in our case, it is ok to have anil
password after creation.An article discussing the issue can be found here.
Solution
Add
allow_nil: true
toUser#password
validation. Also, add tests to ensure the expected validations occur on create and update.