【问题标题】:How to use has_secure_password with field_with_errors如何将 has_secure_password 与 field_with_errors 一起使用
【发布时间】:2012-06-05 22:26:21
【问题描述】:

我正在使用 has_secure_password 来验证我的用户密码及其确认。我遇到的问题是,当有任何错误时,字段没有被 field_with_errors div 包装。我知道我可以添加

validates_presence_of :password, :on => :create
validates_presence_of :password_confirmation, :on => :create

但这会产生以下错误消息:

密码摘要不能为空。
密码不能为空。
密码确认不能为空

我想要么使 has_secure_password 使用 field_with_errors div 包装有错误的字段删除“密码摘要不能为空”。完全错误。

谢谢。

【问题讨论】:

    标签: ruby-on-rails ruby


    【解决方案1】:

    具有此功能的SecurePassword 模块非常简单,值得一看。好消息是,在 the master branch (Rails 4) 中,validates_presence_of :password, :on => :create 可以解决您的问题,但与此同时,您可能希望自己在 User 模型上模仿 has_secure_password 方法。

    class User < ActiveRecord::Base
      attr_reader :password
      attr_accessible :password # ...
      validates_confirmation_of :password
      validates_presence_of :password, on: :create
      include ActiveModel::SecurePassword::InstanceMethodsOnActivation
    end
    

    还要确保 bcrypt 已加载到 Gemfile。

    gem 'bcrypt-ruby', '~> 3.0.0', require: 'bcrypt'
    

    希望对您有所帮助。

    【讨论】:

    • 效果很好。我确实必须添加validates_presence_of :password_confirmation, :on =&gt; :create 以用&lt;div class="field_with_errors"&gt; 包装确认字段,谢谢@ryanb
    【解决方案2】:

    正如@ryanb 所说,validates_presence_of :password 在 master 中是固定的,但不会被反向移植。该修复还清除了Password digest can't be blank. 消息。

    所以,在模型中,还需要添加:

    validates :password, presence: true, on: :create
    

    正如@henrique-zambon 所说,没有必要添加validates_presence_of :password_confirmation。要突出显示密码确认字段,而不显示其他消息,请在显示错误之后在该字段上添加错误。

    然后,要隐藏额外的 Password digest can't be blank. 消息,您只需在表单顶部将其删除即可。

    = form_for @user do |f|
      - if @user.errors.any?
        - @user.errors.delete(:password_digest)
        #error_explanation
          %h2= "#{pluralize(@user.errors.count, "error")} prohibited this user from being saved:"
          %ul
            - @user.errors.full_messages.each do |msg|
              %li= msg
        - @user.errors.add(:password_confirmation) if @user.errors.include?(:password)
    

    【讨论】:

      【解决方案3】:

      无需验证:password_confirmation 的存在,has_secure_password 会为您执行此操作。

      您可能想查看此 RailsCast:Authentication in Rails 3.1

      【讨论】:

      • 谢谢。我知道这一点,但has_secure_password 不与field_with_errors 包装在一起(但验证:password_confirmation 的存在)。这就是我想要完成的。有什么想法吗?
      猜你喜欢
      • 2021-01-02
      • 1970-01-01
      • 2023-03-13
      • 2014-09-25
      • 2016-01-30
      • 2015-12-13
      • 2020-09-15
      • 2020-06-03
      • 2020-11-05
      相关资源
      最近更新 更多