【问题标题】:Update action with empty password使用空密码更新操作
【发布时间】:2016-04-12 14:17:09
【问题描述】:

在 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 包含一个单独的存在验证,该验证专门捕获 nil 密码。

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

此外,rails 怎么知道不给用户设置和保存空密码?请帮帮我。

【问题讨论】:

    标签: ruby-on-rails ruby validation


    【解决方案1】:

    您可以查看文档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] 是空白而不是 nil

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-10-25
      • 1970-01-01
      • 1970-01-01
      • 2020-12-20
      • 1970-01-01
      • 1970-01-01
      • 2020-12-23
      相关资源
      最近更新 更多