gpt4 book ai didi

ruby-on-rails - rails 4 has_secure_password 呈现密码确认可选

转载 作者:行者123 更新时间:2023-12-03 16:13:40 25 4
gpt4 key购买 nike

带 rails 4 我使用 has_secure_password 在我的用户模型中,trick 说如果我不设置 :password_confirmation 它将永远不会被触发,但是为什么当我运行测试时出现错误:密码确认不能为空如下:

Failures:

1) User
Failure/Error: it { should be_valid }
expected #<User id: nil, name: "joe", email: "joe@mail.com", created_at: nil,
updated_at: nil, password_digest: "$2a$04$mcRr/msgYQR3kBVc3kv/m.UotBJuJuSXZKMw
/eHTvU87..."> to be valid, but got errors: Password confirmation can't be blank

我的测试文件看起来像:
require 'spec_helper'

describe User do

before { @user = User.new(name: 'joe', email: 'joe@mail.com', password: 'foo') }

subject { @user }
#....
#....
describe "when password is not present" do
before { @user.password = "" }
it { should_not be_valid }
end
end

为什么我收到这个错误,有解决方案吗?谢谢

最佳答案

长话短说

has_secure_password validations: false # This is the key to the solution
validates :password, presence: true, length: { minimum: 6 } # Or an length you want

长篇大论
  • docsthe source code说:

    If you don’t need the confirmation validation, just don’t set any value to the password_confirmation attribute and the the validation will not be triggered.

  • 但他们也说:

    Validations for presence of password on create, confirmation of password (using a +password_confirmation+ attribute) are automatically added. If you wish to turn off validations, pass validations: false as an argument. You can add more validations by hand if need be.

  • 第 1 项不是完整的描述。我们需要关闭所有验证
    并添加我们自己的验证规则,使这项工作如第 2 点所述。

  • 我花了一些时间在这上面得到了一个教训:当你感到困惑时找到源代码。这似乎是一种痛苦的方式或艰难的方式,但有时它是正确的方式。

    关于ruby-on-rails - rails 4 has_secure_password 呈现密码确认可选,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17954996/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com