如何更改 Rails 4 has_secure_password 状态消息?

How Do I Change Rails 4 has_secure_password Presence Message?

供参考: Rails 4、bcrypt 3.1.7,我用的是simple_form gem

在我的模型中,我有以下代码:

class User < ActiveRecord::Base
  has_secure_password

  validates :email,    presence: {message: 'You must provide an email'},
                         format: { with: /@/, message: 'Please enter a valid email' }
  validates :name,     presence: {message: 'You must enter your first name'}
  # TODO: Make validation message work
  validates :password, presence: {message: 'You must enter a password'},
                         length: {minimum: 8,
                                  message: 'Your password must contain at least 8 characters'}
end

一切都按预期工作,除了密码的存在验证器。我该如何将消息更改为我的消息?

在此处查看 has_secure_password 上的文档:http://api.rubyonrails.org/classes/ActiveModel/SecurePassword/ClassMethods.html

如您所见,您可以取消默认验证:

has_secure_password validations: false

这应该允许您使用自定义密码验证。

请注意,您现在还需要明确添加密码确认验证。这是您可以使用的 has_secure_password 中使用的那个:

validates_confirmation_of :password, allow_blank: true

因此,对于所有内容,您的模型将如下所示:

class User < ActiveRecord::Base
  has_secure_password validations: false

  .
  .
  .

  validates :password, presence: {message: 'You must enter a password'},
                       length: {minimum: 8,
                       message: 'Your password must contain at least 8 characters'}
  validates_confirmation_of :password, allow_blank: true
end

编辑

如果您只想更改消息并仍然使用 has_secure_password 附带的默认验证,您可以编辑 en.yml 文件:

config/locales/en.yml

en:
  activerecord:
    errors:
      models:
        user:
          attributes:
            password:
              blank: "You must enter a password"

然后,对于 :password,您只需添加最低密码验证,因为 has_secure_password:

中不包括
class User < ActiveRecord::Base
  has_secure_password

  .
  .
  .

  validates :password, length: {
    minimum: 8,
    message: 'Your password must contain at least 8 characters'
  }
end