加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – Rails 4.模型中的国家验证

发布时间:2020-12-17 03:49:17 所属栏目:百科 来源:网络整理
导读:我正在创建rails API,并希望为国家/地区字段添加验证,其中包含模型级别的ISO 3166-1代码. 例如,如果使用gem carmen-rails,它只提供helper country_select.是否可以在模型中使用ISO 3166-1代码的国家验证? 解决方法 您只是想验证输入的国家/地区代码是否合适
我正在创建rails API,并希望为国家/地区字段添加验证,其中包含模型级别的ISO 3166-1代码.

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

解决方法

您只是想验证输入的国家/地区代码是否合适?这应该适用于卡门

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

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

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

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读