4

我正在使用 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 包装有错误的字段,或者删除“密码摘要不能为空”。完全错误。

谢谢。

4

3 回答 3

9

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

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'

希望有帮助。

于 2012-06-06T17:05:29.820 回答
5

正如@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)
于 2012-10-08T09:26:47.097 回答
2

无需验证 的存在:password_confirmationhas_secure_password为您执行此操作。

您可能需要检查此 RailsCast:Rails 3.1 中的身份验证

于 2012-06-06T04:34:14.730 回答