Rails 4. Checking the country in the model

I am creating rails APIs and want to add confirmation for a country field that contains ISO 3166-1 code at the model level.

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

+4
source share
3 answers

Are you just trying to confirm that the entered country code is suitable? this should work withcarmen

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

, , , . 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

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 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]}
+4

Fixture , ISO-3166-1 .

, . .

+2

countries gem:

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

All Articles