在 Rails 3 中,当我不尝试更新密码时,如何跳过密码字段的验证? [英] In Rails 3, how can I skip validation of the password field when I'm not attempting to update the password?

查看:42
本文介绍了在 Rails 3 中,当我不尝试更新密码时,如何跳过密码字段的验证?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的用户模型包含:name、:email 和:password 字段.所有 3 个都有长度验证.更新帐户"网页允许用户更新他的姓名和电子邮件地址,但不能密码.提交时,params[:user] 是

My User model contains :name, :email, and :password fields. All 3 have validations for length. An "update account" web page allows the user to update his name and email address, but not password. When submitted, params[:user] is

{"name"=>"Joe User", "email"=>"user@example.com"}

注意没有密码"键,因为表单不包含这样的输入字段.

Note there is no "password" key because the form doesn't contain such an input field.

当我打电话

@user.update_attributes(params[:user])

密码验证失败.但是,由于我没有尝试更新密码,因此我不希望在此更新上运行密码验证.我很困惑为什么在 params[:user] 不包含密码"键时运行密码验证.

the password validation fails. However, since I'm not attempting to update the password, I don't want the password validation to run on this update. I'm confused why the password validation is running when params[:user] doesn't contain a "password" key.

请注意,我想在别处有一个单独的网页,允许用户更新他的密码.对于该提交,密码验证应该运行.

Note that I want to have a separate web page elsewhere that allows the user to update his password. And for that submission, the password validation should run.

谢谢.

推荐答案

我的应用程序做了这样的事情

My application does something like this

attr_accessor :updating_password

validates_confirmation_of :password, :if => should_validate_password?

def should_validate_password?
  updating_password || new_record?
end

因此您必须model.updating_password = true 才能进行验证,而您不必在创建时执行此操作.

so you have to model.updating_password = true for the verification to take place, and you don't have to do this on creation.

我在 http://railscasts.com/episodes/41-条件验证

这篇关于在 Rails 3 中,当我不尝试更新密码时,如何跳过密码字段的验证?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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