我有以下验证:
validates :password, :presence => true, :confirmation => true, :length => { :within => 6..40 }, :format => { :with => pass_regex }, :unless => :nopass?
然后,当我尝试更新没有密码(nopass?为true)出现以下错误:
There were problems with the following fields:
Password is too short (minimum is 6 characters)
Password is invalid
注意:unless适用于:presence和:confirmation,但不适用于:length和:format。
我该如何解决这个问题?
我也有一些关于:确认标志的奇怪问题,我从来没有弄清楚,但这就是我在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
我知道这不是解释为什么你的代码不工作,但如果你正在寻找一个快速的临时修复-我希望这将帮助。
可以使用条件验证
class Person < ActiveRecord::Base
validates :surname, :presence => true, :if => "name.nil?"
end