Selective update attributes

Hello,

I have a user management form with password and password_confirmation fields. I am requiring the fields on create, but they are optional on update. If the user does not supply the password on update I want to leave it alone.

Create works fine. Update works fine if the user supplies a password and confirmation. If the user does not supply a password or confirmation a new blank password is saved.

What is the best way to remove the password from the update statement if it is blank?

Thanks, Dan

Dan Munk wrote:

Hello,

I have a user management form with password and password_confirmation fields. I am requiring the fields on create, but they are optional on update. If the user does not supply the password on update I want to leave it alone.

Create works fine. Update works fine if the user supplies a password and confirmation. If the user does not supply a password or confirmation a new blank password is saved.

What is the best way to remove the password from the update statement if it is blank?

A common way is to store the form-entered passwords in attr_accessors, and only encrypt and write to the DB-backed password-related attributes if the entered passwords were not blank. So when you do a normal save of the user record following entry of blank passwords you'll get the fetched old values of these fields saved straight back.