validates_confirmation_of :密码不会被触发

发布于 2024-12-06 10:18:21 字数 1263 浏览 1 评论 0原文

我有一个非常基本的管理模型:

class Admin < ActiveRecord::Base
  has_secure_password
  validates_uniqueness_of :email
  attr_accessible :email, :password, :password_confirmation
end

根据手册 has_secure_password< /code> 还添加了 validates_confirmation_of :password。如果我是正确的,如果 :password:password_confirmation 不匹配,validates_confirmation_of 应该总是出错 - 即使 :password_confirmation > 是nil

我正在使用 RSpec 进行测试,此测试失败并告诉我 admin is 有效:

admin = Admin.new
admin.email = '[email protected]'
admin.password = 'secret'
admin.should be_invalid

此测试通过:

admin = Admin.new
admin.email = '[email protected]'
admin.password = 'secret'
admin.password_confirmation = ''
admin.should be_invalid

那么,我到底做错了什么?

I have a very basic Admin model:

class Admin < ActiveRecord::Base
  has_secure_password
  validates_uniqueness_of :email
  attr_accessible :email, :password, :password_confirmation
end

According to the manual has_secure_password also adds a validates_confirmation_of :password. If I'm correct validates_confirmation_of should always error if :password and :password_confirmation do not match - even if :password_confirmation is nil.

I'm testing with RSpec and this test fails and tells me that admin is valid:

admin = Admin.new
admin.email = '[email protected]'
admin.password = 'secret'
admin.should be_invalid

This one passes:

admin = Admin.new
admin.email = '[email protected]'
admin.password = 'secret'
admin.password_confirmation = ''
admin.should be_invalid

So, what the heck am I doing wrong?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

送你一个梦 2024-12-13 10:18:21

下面是 has_secure_password 的代码:

# File activemodel/lib/active_model/secure_password.rb, line 32
def has_secure_password
  attr_reader :password

  validates_confirmation_of :password
  validates_presence_of     :password_digest

  include InstanceMethodsOnActivation

  if respond_to?(:attributes_protected_by_default)
    def self.attributes_protected_by_default
      super + ['password_digest']
    end
  end
end

如您所见,它永远不会确保发送密码确认。不过,您可以自己添加,只要您的页面上有表单字段,如果未填写,就会发送一个空字符串。

Here's the code for has_secure_password:

# File activemodel/lib/active_model/secure_password.rb, line 32
def has_secure_password
  attr_reader :password

  validates_confirmation_of :password
  validates_presence_of     :password_digest

  include InstanceMethodsOnActivation

  if respond_to?(:attributes_protected_by_default)
    def self.attributes_protected_by_default
      super + ['password_digest']
    end
  end
end

As you can see it never ensures that a password confirmation is sent. You could add that yourself however, and as long as you have the form field on your page an empty string will be sent if it is unfilled.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文