如何在记录更新期间从验证中排除密码字段? (Rails 3.0.4,Ruby 1.9.2) [英] How do I exclude password fields from validation during record update? (Rails 3.0.4, Ruby 1.9.2)

查看:37
本文介绍了如何在记录更新期间从验证中排除密码字段? (Rails 3.0.4,Ruby 1.9.2)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个允许更新用户记录的表格。它包含:password和:password_confirmation的字段,但我希望如果已在数据库中存储了加密密码,则对它们运行验证。

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.

视图文件中的字段:

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

在搜索互联网时,我发现了这段代码,我认为这是以前版本的Ruby / Rails。 (我会将其放在用户模型中。)

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.

谢谢。

编辑-插入以下代码,它确实允许用户记录更新,而不会抱怨密码字段丢失。

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


推荐答案

我建议您执行以下操作:

I would recommend doing the following:

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

这基本上表示在创建密码时需要使用password_confirmation确认密码,并且还需要当密码不为零时(例如,用户更新其密码时)将被确认。

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.

这篇关于如何在记录更新期间从验证中排除密码字段? (Rails 3.0.4,Ruby 1.9.2)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆