本文介绍了Rails 4.模型中的国家/地区验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建Rails API,并想添加对国家/地区字段的验证,该字段包含模型级别的ISO 3166-1代码.

I'm creating rails API and want to want to add validation for countries field which contains an ISO 3166-1 code on model level.

例如,如果使用gem carmen-rails ,则它仅提供帮助器country_select.是否可以在模型中对符合国家/地区的ISO 3166-1代码进行验证?

For example if use gem carmen-rails, it provides only helper country_select. Is that way to use validation for accordance country for ISO 3166-1 code in the model?

推荐答案

您只是在尝试验证输入的国家/地区代码是否合适?这应该与carmen

You are just trying to validate that the country code entered is appropriate? this should work with carmen

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

但是,如果这仅是您所需要的,则国家/地区宝石可能也可以很好地工作.使用countries,您可以

But if this is all you need seems like the countries gem might work well too. With countries you could do

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,您可以像这样同时验证所有3个.

For Region and State you can validate all 3 at the same time like this.

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

尽管地区似乎没有必要,因为您可能暗示像

Although Region seems unnecessary as you could imply this from the country like

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

这篇关于Rails 4.模型中的国家/地区验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-26 03:38