Der*_*153 4 ruby validation model ruby-on-rails ruby-on-rails-4
我正在创建rails API,并希望为国家/地区字段添加验证,其中包含模型级别的ISO 3166-1代码.
例如,如果使用gem carmen-rails,它只提供帮助country_select.是否可以在模型中使用ISO 3166-1代码的国家验证?
这是使用countriesgem进行验证的最新语法:
validates :country, inclusion: { in: ISO3166::Country.all.map(&:alpha2) }
Run Code Online (Sandbox Code Playgroud)
您只是想验证输入的国家/地区代码是否合适?这应该适用carmen
validates :country, inclusion:{in:Carmen::Country.all.map(&:code)}
Run Code Online (Sandbox Code Playgroud)
但如果这就是你所需要的,那么看起来这些国家的宝石也可能运作良好.随countries你可以做
validates :country, inclusion:{in:Country.all.map(&:pop)}
Run Code Online (Sandbox Code Playgroud)
要么
validate :country_is_iso_compliant
def country_is_iso_compliant
errors.add(:country, "must be 2 characters (ISO 3166-1).") unless Country[country]
end
Run Code Online (Sandbox Code Playgroud)
更新
对于Region和State,您可以像这样同时验证所有3个.
validates :country, :region, :state, presence: true
validate :location
def location
current_country = Country[country]
if current_country
#valid regions would be something Like "Europe" or "Americas" or "Africa" etc.
errors.add(:region, "incorrect region for country #{current_country.name}.") unless current_country.region == region
#this will work for short codes like "CA" or "01" etc.
#for named states use current_country.states.map{ |k,v| v["name"}.include?(state)
#which would work for "California" Or "Lusaka"(it's in Zambia learn something new every day)
errors.add(:state, "incorrect state for country #{current_country.name}.") unless current_country.states.keys.include?(state)
else
errors.add(:country, "must be a 2 character country representation (ISO 3166-1).")
end
end
Run Code Online (Sandbox Code Playgroud)
虽然地区似乎没必要,因为你可以从国家这里暗示这一点
before_validation {|record| record.region = Country[country].region if Country[country]}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2287 次 |
| 最近记录: |