本文介绍了Rails 4.模型中的国家和地区/州验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一张桌子User
create_table :users do |t|
t.string :first_name
t.string :last_name
t.string :country
t.string :region
t.string :city
t.timestamps
end
我需要验证国家和地区,还检查地区是否属于国家.我将宝石国家/地区用于国家/地区验证.
I need to validate country and region, also check does region belongs to country.I use gem countries for country validation.
#user.rb
class User < ActiveRecord::Base
validates_inclusion_of :country, in:Country.all.map(&:pop), :message => "wrong country format"
end
如何对区域"使用验证并检查区域是否属于国家
How can I use validation for 'region' and check does region belongs to country
更新
使用@engineersmnky的建议
Using @engineersmnky's advice
#user.rb
validates :country, :region, presence: true
validate :location
def location
current_country = Country[country]
if current_country
errors.add(:region, "incorrect state for country #{current_country.name}.") unless current_country.map{ |k,v| v["name"]}.include?(region)
else
errors.add(:country, "must be a 2 character country representation (ISO 3166-1).")
end
end
在控制台中对此进行测试:
Test this in console:
2.1.2 :001 > u = User.new(country:"US", region:"SomeState")
=> #<User id: nil, first_name: nil, last_name: nil, country: "US", region: "SomeRegion", city: nil, address: nil, zip: nil, phone: nil, company: nil, created_at: nil, updated_at: nil>
2.1.2 :002 > u.valid?
NoMethodError: undefined method `map' for #<Country:0x007fefb16dd140>
哪里有错误?或我了解错误的地方:(
Where is mistake? or I understand something wrong :(
推荐答案
从我以前的帖子中删除
Moved from my previous post Here
尽管现在我按地区看到您指的是国家/地区
Although now I see by region you mean state
您也可以这样做
#optionally in:lambda{|user| Country[user.country].states.map{ |k,v| v["name"]}}
#for named states see below for further explanation
validate_inclusion_of :region, in:lambda{ |user| Country[user.country].states.keys}, if: lambda{ |user| Country[user.country]}
对于国家和地区/州,您可以像这样同时验证两者.
For Country and Region/State you can validate both at the same time like this.
validates :country, :region, presence: true
validate :location_by_country
def location_by_country
current_country = Country[country]
if current_country
#this will work for short codes like "CA" or "01" etc.
#for named regions use:
# current_country.states.map{ |k,v| v["name"]}.include?(region)
#which would work for "California" Or "Lusaka"(it's in Zambia learn something new every day)
#for Either/Or use:
# current_country.states.map{|k,v| [k,v["name"]]}.flatten
#this will match "California" OR "CA"
errors.add(:region, "incorrect region for country #{current_country.name}.") unless current_country.states.keys.include?(region)
else
#optionally you could add an error here for :region as well
#since it can't find the country
errors.add(:country, "has wrong country format")
end
end
这篇关于Rails 4.模型中的国家和地区/州验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!