首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >在Rails 3.2中使用has_secure_password时如何禁用密码/确认验证?

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

Stack Overflow用户
提问于 2012-03-18 15:08:50
回答 2查看 4.7K关注 0票数 16

我有一个这样设置的用户模型:

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验证,除非用户尝试更改其密码。

因此,如果用户在没有指定密码和/或确认的情况下更新表单中的信息,应该会成功。如果用户更新其信息并包括密码和/或确认,则应运行验证。

实现这一目标的最佳方法是什么?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2012-03-18 15:53:31

您可以向两个验证器添加一个条件: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:

或者使用一个方法进行验证,将验证检查移动到该方法中,而不是作为单独的validates调用:

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
票数 21
EN

Stack Overflow用户

发布于 2018-04-17 20:55:15

除了Zabba的answer之外,选项1也可以这样写:

with_options if: :password_provided? do
    validates :password, :password_confirmation, presence: true, length: { minimum: 12 }
end

def password_provided?
    password.present? || password_confirmation.present?
end
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/9756652

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档