我有以下验证:
validates :password, :presence => true, :confirmation => true, :length => { :within => 6..40 }, :format => { :with => pass_regex }, :unless => :nopass?
然后,当我尝试更新时没有密码(nopass?为真)时会出现以下错误:
There were problems with the following fields:
Password is too short (minimum is 6 characters)
Password is invalid
请注意:除非适用于:在线和:确认但不在:lenght或:format。
我该如何解决这个问题?
答案 0 :(得分:1)
我也遇到了一些奇怪的问题:确认标志,我从未想过,但这就是我在Rails 3.0.x应用程序中解决问题的方法:
attr_accessor :password_confirmation
validates :password, :presence => true, :length => {:within => PASSWORD_MIN_LENGTH..PASSWORD_MAX_LENGTH}
validate :password_is_confirmed
def password_is_confirmed
if password_changed? # don't trigger that validation every time we save/update attributes
errors.add(:password_confirmation, "can't be blank") if password_confirmation.blank?
errors.add(:password_confirmation, "doesn't match first password") if password != password_confirmation
end
end
我意识到这并不能解释为什么你的代码无效,但是如果你正在寻找一个快速的临时修复 - 我希望这会有所帮助。
答案 1 :(得分:0)
class Person < ActiveRecord::Base
validates :surname, :presence => true, :if => "name.nil?"
end