You could add a before_update
callback to your model to strip blanks.
class User before_update -> { self.restore_password! if self.password.blank? } ...end
However, model callbacks can cause problems, especially when they're enforcing "business" rules which can change or not be universally applicable. And sometimes callbacks are skipped and they can complicate bulk database updates. This is the "fat model" problem.
Instead, do this as a model validation.
class User validates :password, presence: true ...end
Normally you'd leave it at that and use the validation to inform the user of the problem.
If you want to update the other user attributes even if one of them is invalid, this is a questionable practice, you'd delete the blank password parameter in your controller. A better reason is if the user accidentally puts a space in the password field or something.
class UserController ... def update # or `params.compact_blank!` to do this for all parameters params.delete(:password) if params[:password].blank? ... endend
But don't reinvent user accounts. Use devise
. It's secure, well documented, and it works with many other gems.