使用空密码更新操作

时间:2016-04-12 14:17:09

标签: ruby-on-rails ruby validation

在Michael Hartl的教程中,陈述如下。

class User < ActiveRecord::Base
attr_accessor :remember_token
before_save { self.email = email.downcase }
validates :name, presence: true, length: { maximum: 50 }
VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
validates :email, presence: true, length: { maximum: 255 }
                format: { with: VALID_EMAIL_REGEX },
                uniqueness: { case_sensitive: false }
has_secure_password
validates :password, presence: true, length: { minimum: 6 }, allow_nil: true

end

如果您担心清单9.10可能允许新用户注册空密码,请回顾第6.3.3节,has_secure_password包含一个单独的状态验证,专门捕获零密码。

我的问题是,如果允许测试通过,has_secure_password验证如何工作?我不明白,显然has_secure_password验证没有“捕获”此规则以绕过空密码。

此外,rails如何知道不将空密码设置并保存给用户?请帮帮我。

1 个答案:

答案 0 :(得分:0)

您可以查看文档here,它会详细解释所有内容,

根据源代码:

def has_secure_password
   .....
   if options.fetch(:validations, true)
     include ActiveModel::Validations

   # This ensures the model has a password by checking whether the password_digest
   # is present, so that this works with both new and existing records. However,
   # when there is an error, the message is added to the password attribute instead
   # so that the error message will make sense to the end-user.
     validate do |record|
       record.errors.add(:password, :blank) unless record.password_digest.present?
     end

     validates_length_of :password, maximum: ActiveModel::SecurePassword::MAX_PASSWORD_LENGTH_ALLOWED
     validates_confirmation_of :password, allow_blank: true
   end
   ..........
end

如果您没有致电has_secure_password(validations: false),则会添加三种类型的验证。我认为通过考试的原因是:

validates :password, presence: true, length: { minimum: 6 }, allow_nil: true
  

:allow_nil选项在值为时跳过验证   验证是零。

添加

  

rails如何知道不设置空密码并将其保存到   用户?

我认为这是因为params[:user][:password]是空白而不是