6

I have a form which permits updating of a user record. It contains fields for :password and :password_confirmation but I do not want validation to run on them if an encrypted password is already stored in the database.

The fields from the view file:

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

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

validates_presence_of :password, :on => create

As the syntax for my password validation in my user model is different (below), I'm confused about the syntax I would need.

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

I have searched other posts and sure could use some direction.

-- Disclaimer -- I did see that there is a screen cast about conditional validations but I'm not able to watch it at the moment.

Thanks, all.

Edit - inserted the following code and it does permit a user record update without complaining about the password field missing.

validates :password, :presence => true, :confirmation => true, :on => :create
Tass
  • 1,628
  • 16
  • 28
  • Of course I (kind of) resolved this issue as soon as I posted my question. However, I think my resolution (which I added at the bottom of my question) isn't a proper fix and I'll run into problems in the future when I begin changing passwords. – Tass Apr 06 '11 at 20:39
  • But how would this be handled if there is an update. Like you are doing something like a reset password or a change password? – Kevin Horvath Nov 09 '14 at 08:39
  • @KevinHorvath -- Your question is outside of the scope of this topic. Did your search lead you here? – Tass Nov 11 '14 at 17:29

2 Answers2

8

I would recommend doing the following:

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

This basically says that a password needs to be confirmed on creation with password_confirmation and that it also needs to be confirmed when password is not nil - for example when the user is updating their password.

Pan Thomakos
  • 34,082
  • 9
  • 88
  • 85
  • Thank you very much, Pan. I commented out my most recent changes, added your code and then successfully updated a user record. Exactly what I needed. – Tass Apr 06 '11 at 20:44
5
validates :password, :presence => true, :confirmation => true, :on => :create

Read more on Railsguides: http://edgeguides.rubyonrails.org/active_record_validations_callbacks.html#on

Markus Proske
  • 3,356
  • 3
  • 24
  • 32
  • Markus, as you can see (there's a bit of lag on my end regarding edits/comments) I ended up trying your solution as well. Thanks! And thanks for the link as well. – Tass Apr 06 '11 at 20:47