【问题标题】:Model validations模型验证
【发布时间】:2011-09-08 09:35:01
【问题描述】:

是否可以检查:password字段中输入的内容是否与模型中的:current_password字段不同?

类似

validates :current_password, :format => { :with => :password, :message => "Current password can't be the same as the password" }

哪个行不通,正确的写法是什么?

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 validation model


    【解决方案1】:

    首先,希望您不要将密码存储为纯文本

    其次,自定义验证将为您工作:

    validate :password_is_not_the_same
    
    def password_is_not_the_same
      errors.add(:password, 'Current password can\'t be the same as the password') if BCrypt::Password.new(password_digest) == password
    end
    

    编辑:

    validate :password_is_not_the_same
    
    def password_is_not_the_same
      errors.add(:password, 'Current password can\'t be the same as the password') if current_password == password
    end
    

    【讨论】:

    • 不起作用如何检查 :current_password ? ,我只是想确保他们放入 current_password 字段的任何内容都与该字段的密码不同,并给出错误提示它们不能相同
    • 您的密码是如何存储的? (希望不是)作为纯文本,作为 MD5/SHA 哈希,还是使用 Bcyrpt? (此示例假设您使用的是 Bcrypt。)
    • 但我不想检查数据库中的密码值,我只想检查他们在表单中输入的内容以及表单中的 current_password。
    • 所以current_password 是模型中包含纯文本密码的字段?
    • 不,不是,我只是想检查在 current_password 字段中输入的内容与在“新”密码字段中输入的内容不同。只是一个简单的客户端检查。
    猜你喜欢
    • 1970-01-01
    • 2019-01-11
    • 2017-08-16
    • 2014-01-07
    • 2013-08-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多