我有以下用户模型:
class User < ActiveRecord::Base
# Users table has the necessary password_digest field
has_secure_password
attr_accessible :login_name, :password, :password_confirmation
validates :login_name, :presence=>true, :uniqueness=>true
# I run this validation on :create so that user
# can edit login_name without having to enter password
validates :password,:presence=>true,:length=>{:minimum=>6},:on=>:create
# this should only run if the password has changed
validates :password_confirmation,
:presence=>true, :if => :password_digest_changed?
end
这些验证并没有完全达到我的期望。以下操作是可能的:
# rails console
u = User.new :login_name=>"stephen"
u.valid?
# => false
u.errors
# => :password_digest=>["can't be blank"],
# => :password=>["can't be blank", "please enter at least 6 characters"]}
# so far so good, let's give it a password and a valid confirmation
u.password="password"
u.password_confirmation="password"
# at this point the record is valid and does save
u.save
# => true
# but we can now submit a blank password from console
u.password=""
# => true
u.password_confirmation=""
# => true
u.save
# => true
# oh noes
我希望您能做以下事情:
- 创建时需要密码,密码长度必须为6个字符
- 在创建时需要确认密码,确认密码必须与密码匹配
- 用户在更新登录名时不必提交密码
- 密码不能在更新时被删除
password_changed?
而不是:password_digest_changed?
,Rails会抛出一个“no method”错误。我不明白为什么。请问有人知道我做错了什么吗?
:presence
验证,因为secure_password
已经检查了:password_digest
的存在。我制作了一个gist以便将来提醒自己。 - stephenmurdoch