How to exclude password fields from verification during record update? (Rails 3.0.4, Ruby 1.9.2)

I have a form that allows me to update a user post. It contains the fields for: password and: password_confirmation, but I do not want the verification to be performed on them if the encrypted password is already stored in the database.

Fields from the view file:

<%= f.password_field :password %> <%= f.password_field :password_confirmation, :label => 'Confirm Password' %> 

When searching the Internet, I found this bit of code, which I believe was for a previous version of Ruby / Rails. (Which I would place in my user model.)

 validates_presence_of :password, :on => create 

Since the password verification syntax in my user model is different (below), I am confused by the syntax I need.

 validates :password, :presence => true, :confirmation => true 

I was looking for other posts and could use some direction.

- Disclaimer - I saw that there is a screen dedicated to conditional checks, but I can not watch it at the moment.

Thank you all.

Edit - inserted the following code, and it allows you to update the user record without complaining about the lack of a password field.

 validates :password, :presence => true, :confirmation => true, :on => :create 
+4
source share
2 answers

I would recommend doing the following:

 validates :password, :presence => true, :confirmation => true, :if => lambda{ new_record? || !password.nil? } 

This basically means that the password must be confirmed when creating with password_confirmation and that it also needs to be confirmed when the password is not zero - for example, when the user updates his password.

+7
source
 validates :password, :presence => true, :confirmation => true, :on => :create 

More information about Railsguides: http://edgeguides.rubyonrails.org/active_record_validations_callbacks.html#on

+4
source

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


All Articles