gpt4 book ai didi

ruby-on-rails - (设计)更新时需要密码,即使它是空白的

转载 作者:太空宇宙 更新时间:2023-11-03 17:25:00 25 4
gpt4 key购买 nike

我的用户模型无法保存,因为 password 和 password_confirmation 不能为空。这发生在:

  • 在 edit_user_registration 上更新用户并将密码和密码确认留空。这是我第一次注意到的地方
  • 在控制台上,加载对象并调用保存后立即执行。

如果需要 password_required,Devise 将验证密码是否存在?

  validates_presence_of     :password, :if => :password_required?

def password_required?
!persisted? || !password.nil? || !password_confirmation.nil?
end

这是我的 Rails 控制台输出:

  Loading development environment (Rails 3.2.11)
1.9.3p374 :001 > u = User.last
User Load (1.0ms) SELECT "users".* FROM "users" ORDER BY "users"."id" DESC LIMIT 1
=> #<User id: 9, name: "Name", email: "name@example.com", encrypted_password: "$2a$10$oCL2K0nEa8LxaMGuC1oyNOuwIHk8l/IOW.AylGcWTYj3...", reset_password_token: nil, reset_password_sent_at: nil, remember_created_at: nil, sign_in_count: 2, current_sign_in_at: "2013-02-06 20:56:14", last_sign_in_at: "2013-02-06 20:52:01", current_sign_in_ip: "127.0.0.1", last_sign_in_ip: "127.0.0.1", confirmation_token: nil, confirmed_at: "2013-02-07 22:04:01", confirmation_sent_at: "2013-02-07 22:03:25", unconfirmed_email: nil, authentication_token: nil, created_at: "2013-02-06 20:52:00", updated_at: "2013-02-07 22:04:31">
1.9.3p374 :002 > u.save
(0.2ms) BEGIN
(0.2ms) ROLLBACK
=> false
1.9.3p374 :003 > u.errors
=> #<ActiveModel::Errors:0x007f832c04f090 @base=#<User id: 9, name: "Name", email: "name@example.com", encrypted_password: "$2a$10$oCL2K0nEa8LxaMGuC1oyNOuwIHk8l/IOW.AylGcWTYj3...", reset_password_token: nil, reset_password_sent_at: nil, remember_created_at: nil, sign_in_count: 2, current_sign_in_at: "2013-02-06 20:56:14", last_sign_in_at: "2013-02-06 20:52:01", current_sign_in_ip: "127.0.0.1", last_sign_in_ip: "127.0.0.1", confirmation_token: nil, confirmed_at: "2013-02-07 22:04:01", confirmation_sent_at: "2013-02-07 22:03:25", unconfirmed_email: nil, authentication_token: nil, created_at: "2013-02-06 20:52:00", updated_at: "2013-02-07 22:04:31">, @messages={:password=>["can't be blank"], :password_confirmation=>["can't be blank"]}>
1.9.3p374 :004 > !u.persisted? || !u.password.nil? || !u.password_confirmation.nil?
=> false

感谢您的帮助!

最佳答案

感谢@rainkinz,我回到了基础(用户模型)并仔细观察。我发现我正在导入的模块添加了一个额外的

validates :email, :password, :password_confirmation, presence: true

我可以通过在控制台中运行来看到这一点:

User.validators

...
#<ActiveModel::Validations::PresenceValidator:0x007fb80fbcd260
@attributes=[:email, :password, :password_confirmation],
@options={}>,
...

这与设计放入的验证不同,后者包含:

@options={:if=>:password_required?}>,

删除那些解决了问题。感谢您的帮助!

关于ruby-on-rails - (设计)更新时需要密码,即使它是空白的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14762028/

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