如何在Rails 3.2中使用has_secure_password时禁用密码/确认验证?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (1)
  • 关注 (0)
  • 查看 (44)

我有一个用户模型设置如下:

class User < ActiveRecord::Base
  has_secure_password

  # callbacks -------------------------------------------------------------------------
  before_create { generate_token(:auth_token) }

  # setup accessible (or protected) attributes for your model and validation ----------
  attr_accessible :email, :password, :password_confirmation

  # validations
  VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
  validates :email    , presence: true,
                        uniqueness: { case_sensitive: false },
                        format: { with: VALID_EMAIL_REGEX }

  validates :password             , length: { minimum: 6 } 

  validates :password_confirmation, presence: true

但是我不想在更新用户时运行密码和/或password_confirmation验证,除非用户尝试更改密码。

所以,如果用户在没有指定密码和/或确认的情况下更新他们的信息,它应该成功。如果用户更新他们的信息并且包含密码和/或确认,则验证应该运行。

如何做到?

提问于
用户回答回答于

可以添加一个条件:if对于两个验证器:

1:

validates :password             , length: { minimum: 6 }, :if => :validate_password?
validates :password_confirmation, presence: true        , :if => :validate_password?

def validate_password?
  password.present? || password_confirmation.present?
end

2:

validate :check_password, :on => :update

def check_password
  return unless password.present? || password_confirmation.present?
  ..validations for both attributes here.. 
  ..check presence, length etc. as required and add to the errors variable as necessary..
end

扫码关注云+社区

领取腾讯云代金券