Rails 4.模型中的国家validation

我正在创建rails API,并希望为国家/地区字段添加validation,其中包含模型级别的ISO 3166-1代码。

例如,如果使用gem carmen-rails ,它只提供helper country_select 。 是否可以在模型中使用ISO 3166-1代码的国家validation?

您只是想validation输入的国家/地区代码是否合适? 这应该适用于carmen

 validates :country, inclusion:{in:Carmen::Country.all.map(&:code)} 

但如果这就是你所需要的,那么看起来国家的gem也可能运作良好。 有了你可以做的countries

 validates :country, inclusion:{in:Country.all.map(&:pop)} 

要么

 validate :country_is_iso_compliant def country_is_iso_compliant errors.add(:country, "must be 2 characters (ISO 3166-1).") unless Country[country] end 

更新

对于Region和State,您可以像这样同时validation所有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 

虽然地区似乎没必要,因为你可以从国家这里暗示这一点

 before_validation {|record| record.region = Country[country].region if Country[country]} 

使用维基百科在ISO-3166-1上提供的数据创建一个Fixture,并根据该数据validation该国家/地区。

您还可以创建一个自动完成function来简化输入。 您可以查看此处提供的自动完成function以获取指导。

以下是使用countries gem进行validation的最新语法:

 validates :country, inclusion: { in: ISO3166::Country.all.map(&:alpha2) }