Quantcast
Channel: User Schwern - Stack Overflow
Viewing all articles
Browse latest Browse all 581

Answer by Schwern for How to prevent password from being updated if blank in Rails Model and test it with RSpec?

$
0
0

You could add a before_updatecallback 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.


Viewing all articles
Browse latest Browse all 581

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>