我正在爲省和國家創建Rails遷移。這個想法是,對於每個國家,我們不能允許一個以上的同名省份。
我create_provinces遷移:has_many on Rails遷移的唯一性(不通過)
class CreateProvinces < ActiveRecord::Migration
def change
create_table :provinces do |t|
t.string :name
t.references :country, index: true, foreign_key: true
end
end
我country.rb是:
class Country < ActiveRecord::Base
has_many :provinces, :uniq => true
end
我province.rb是:
class Province < ActiveRecord::Base
belongs_to :country
private
validates_presence_of :country
validate :canada_or_usa?
validates_presence_of :name
validate :in_right_country?
validates_associated :country
def canada_or_usa?
errors.add(:country, "can only add province for Canada or the United States") unless (country.name == "Canada" || country.name == "United States")
end
def in_right_country?
if country.name == "Canada"
errors.add(:name, "Name must be the name of a province in Canada") unless (DataHelper::canada_provinces_with_caption.include? name)
end
if country.name == "United States"
errors.add(:name, "Name must be the name of a province in the United States") unless (DataHelper::usa_provinces_with_caption.include? name)
end
end
end
隨着country.rb :uniq => true
,我得到這樣的錯誤:uniq不是已知的關鍵。請注意,我也沒有按照其他問題使用through
。有沒有辦法確保每個國家不能有兩個同名的省份?