我的用戶模型無法保存,因爲密碼和password_confirmation不能爲空。發生這種情況時:(設計)更新時需要密碼,即使它留空白
- 在edit_user_registration上更新用戶並將密碼和密碼確認留空。這是我第一次注意到的地方
- 在控制檯上,加載對象並調用保存後立即。
如果password_required設計會驗證密碼的存在嗎?
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: "[email protected]", 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: "[email protected]", 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
感謝您的幫助!
你可以發佈你的整個用戶模型嗎?這裏一定還有別的事情要做。奇怪的是,你得到:password_confirmation => [「不能空白」]錯誤。你有某個地方的驗證? – rainkinz
感謝您的幫助!它必須在別的地方,稍後再睡一晚,你的建議很明顯。我回答我自己的問題來解釋這個問題。再次感謝! – Leito