我正在阅读Michael Hartl的 Ruby On Rails教程(第3版)。在第9章中,有一个示例向我们展示了如何更新用户信息。我对这里附带的allow_nil感到困惑。我将代码简化如下:
class User < ActiveRecord::Base
has_secure_password
validates :password, presence: true, length: { minimum: 6 }, allow_nil: true
end
myuser=User.new(name: "Foo_bar",email: "test@example.com", password: "123456", password_confirmation: "123456")
myuser.save
myuser=User.find(myuser.id)
myuser.update_attributes(name: "Bar_Foo",email: "test@example.com", password: "", password_confirmation: "") # It will succeed! But WHY?
我理解当验证的值为nil时,allow_nil: true
会跳过验证。然而很明显,password: ""
不是零值。 allow_nil: true
如何允许空字符串?
答案 0 :(得分:1)
您可以在irb中尝试:
user = User.new
user.password = '123'
user.password_confirmation = '123'
user.password_digest.nil? => false
user = User.new
user.password = ''
user.password_confirmation = ''
user.password_digest.nil? => true
答案 1 :(得分:1)
此行为归因于has_secure_password
魔法。简而言之,它检查给定的密码是否为空,如果是,则不向@password
分配任何内容。因此:
user = User.new
user.password = '' # This is not an assignment, but invocation of `password=` method.
user.password #=> nil
您可以在此处查看password=
方法背后的源代码:https://github.com/rails/rails/blob/869a90512f36b04914d73cbf58317d953caea7c5/activemodel/lib/active_model/secure_password.rb#L122
另请注意,has_secure_password
已定义默认密码验证,因此如果您要创建自己的密码验证,则需要使用has_secure_password validation: false