我的用户模型无法保存,因为密码和密码确认不能为空。这发生在:
- 在 edit_user_registration 上更新用户并将密码和密码确认留空。这是我第一次注意到的地方
- 在控制台上,在加载对象并调用 save 之后立即。
如果 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: "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
谢谢你的帮助!