开发者

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

开发者 https://www.devze.com 2023-02-22 08:31 出处:网络
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

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开发者_如何学Python permit a user record update without complaining about the password field missing.

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


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.


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

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

0

精彩评论

暂无评论...
验证码 换一张
取 消