2015-07-21 81 views

回答

2

你不能做到这一点; if将在类定义处进行评估,而不是在验证时进行评估。你要么需要使用:if选项:

validates_length_of :phone, :minimum => 10, :maximum => 10, 
    :if => Proc.new { |x| x.country_code == 91 } 

,或者你需要使用一个自定义的验证,是这样的:

PHONE_LENGTH_LIMITS_BY_COUNTRY_CODE = { 
    91 => [10, 10] 
} 
def phone_number_is_correct_according_to_country_code 
    min, max = *PHONE_LENGTH_LIMITS_BY_COUNTRY_CODE[country_code] 
    if phone.length < min || phone.length > max 
    errors.add(:phone, "must be between #{min} and #{max} characters") 
    end 
end 
validate :phone_number_is_correct_according_to_country_code 

(免责声明:未经测试的代码)

相关问题