Skip checking for some members of the Devise model during password reset

The My User (Devise) model also has a name, city, nation, phone members.

On the registration creation page - I validates_presence_of city, nation, phone, name, email, :on => :create

On the rights editing page - I validates_presence_of city, nation, phone, name, :on => :update

Now, when I set a new password on the forget_password_page page, it requests the presence of the city, country, phone, name inside Devise::PasswordsController#update

How can I handle spot checks?

I assume this should be something like:

 validates_presence_of city, nation, phone, name, :on => :update, :if => :not_recovering_password def not_recovering_password # what goes here end 
+4
source share
4 answers
+2
source

I had a similar problem, because when my User is created, not all of its fields are required. The presence of other fields is checked on: :update by checking.

So this is how I decided:

 validates :birthdate, presence: true, on: :update, unless: Proc.new{|u| u.encrypted_password_changed? } 

encrypted_password_changed? method encrypted_password_changed? is the one used in Devise Recoverable .

+7
source

I stumbled upon this question looking for an answer to a similar question, so hopefully someone finds this useful. In my case, I was dealing with outdated data that lacked information for fields that were not previously needed, but were later needed. Here is what I did, essentially, to finish the code above:

 validates_presence_of city, nation, phone, name, :on => :update, :if => :not_recovering_password def not_recovering_password password_confirmation.nil? end 

Basically, it uses the absence / presence of the password_confirmation field to find out if the user is trying to change / reset his password. If it is not full, they do not change it (and thus run the check). If it is full, they change / reload and so you want to skip your checks.

+2
source

In the Devise model, you can override reset_password! and use your own checks. For instance:

 def reset_password!(new_password, new_password_confirmation) self.password = new_password self.password_confirmation = new_password_confirmation validates_presence_of :password validates_confirmation_of :password validates_length_of :password, within: Devise.password_length, allow_blank: true if errors.empty? clear_reset_password_token after_password_reset save(validate: false) end end 
+1
source

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


All Articles