Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I exclude password fields from validation during record update? (Rails 3.0.4, Ruby 1.9.2)

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
like image 473
Tass Avatar asked Apr 06 '11 20:04

Tass


1 Answers

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.

like image 52
Pan Thomakos Avatar answered Sep 27 '22 20:09

Pan Thomakos