ActiveRecord多个自定义长度验证

时间:2016-10-28 12:40:39

标签: ruby-on-rails validation ruby-on-rails-4 model rails-activerecord

我有Address模型,我需要根据:zipcode验证:country长度。

例如:

  • 如果:country == 'us',则最长:zipcode长度应为5
  • 如果:country == 'br',则最长:zipcode长度应为8

等等......

我正在运行Ruby on Rails 4.2.7。

1 个答案:

答案 0 :(得分:2)

class Address < ActiveRecord::Base
  ZIP_CODE_VALIDATION = { 'us' => 5, 'br' => 8 }.freeze                 

  validate :zip_code_by_country

  def max_length
    ZIP_CODE_VALIDATION[country]
  end

  def zip_code_by_country      
    return unless zipcode.length > max_length
    errors.add(:zipcode, "can't be greater than #{max_length}")
  end
end