How to use has_secure_password with the_with_errors_field

I use has_secure_password to verify the user password and confirm it. The problem is that when there are any errors, the fields are not wrapped by field_with_errors. I know I can add

validates_presence_of :password, :on => :create validates_presence_of :password_confirmation, :on => :create 

but this creates the following error message:

Digest password cannot be empty.
Password cannot be empty.
Password confirmation cannot be empty

I would either make has_secure_password wrap the error fields using the field_with_errors div or delete the "Password password cannot be empty." mistake at all.

Thanks.

+4
source share
3 answers

The SecurePassword module, which has this functionality, is quite simple and deserves attention. The good news is that in the main branch (Rails 4) it executes validates_presence_of :password, :on => :create , which will solve your problem, but in the meantime you might want to has_secure_password method on the user model yourself.

 class User < ActiveRecord::Base attr_reader :password attr_accessible :password # ... validates_confirmation_of :password validates_presence_of :password, on: :create include ActiveModel::SecurePassword::InstanceMethodsOnActivation end 

Also make sure bcrypt loaded in the gemfile.

 gem 'bcrypt-ruby', '~> 3.0.0', require: 'bcrypt' 

Hope this helps.

+9
source

As @ryanb stated, validates_presence_of :password is fixed in master, but will not be passed. This fix also clears the Password digest can't be blank. message Password digest can't be blank. .

So, in the model, you still need to add:

 validates :password, presence: true, on: :create 

As pointed out by @ henrique-zambon, there is no need to add a validates_presence_of :password_confirmation . To highlight the password confirmation field without showing this additional message, add an error to this field after you have indicated errors.

Then, to hide the optional Password digest can't be blank. message Password digest can't be blank. , you can simply delete it at the top of the form.

 = form_for @user do |f| - if @user.errors.any? - @user.errors.delete(:password_digest) #error_explanation %h2= "#{pluralize(@user.errors.count, "error")} prohibited this user from being saved:" %ul - @user.errors.full_messages.each do |msg| %li= msg - @user.errors.add(:password_confirmation) if @user.errors.include?(:password) 
+5
source

No need to check for availability :password_confirmation , has_secure_password does this for you.

You can check out this RailsCast: Authentication in Rails 3.1

+2
source

Source: https://habr.com/ru/post/1416263/


All Articles