如何将has_secure_password与field_with_errors一起使用

T. *_*all 4 ruby ruby-on-rails

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

validates_presence_of :password, :on => :create
validates_presence_of :password_confirmation, :on => :create
Run Code Online (Sandbox Code Playgroud)

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

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

我想要么使has_secure_password包裹有错误的字段有field_with_errors股利删除"密码摘要不能为空." 一共错误.

谢谢.

rya*_*anb 9

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

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
Run Code Online (Sandbox Code Playgroud)

还要确保bcrypt在Gemfile中加载.

gem 'bcrypt-ruby', '~> 3.0.0', require: 'bcrypt'
Run Code Online (Sandbox Code Playgroud)

希望有所帮助.


小智 5

正如@ryanb所说,它validates_presence_of :password是固定在主人身上,但不会被后移.该修复程序也清除了该Password digest can't be blank.消息.

因此,在模型中,您仍需要添加:

validates :password, presence: true, on: :create
Run Code Online (Sandbox Code Playgroud)

正如@ 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)
Run Code Online (Sandbox Code Playgroud)