私は、地域と国のためのRails移行を作成しています。アイデアは、各国のために同じ名前の複数の州を許可することはできないということです。
マイcreate_provincesの移行は、次のとおりです。Railsの移行でのhas_manyの一意性(スルーなし)
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は次のとおりです。
country.rbで:uniq => true
で
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
、私はuniqは既知のキーではありません。他の質問につきましてはthrough
も使用していないことにご注意ください。各国が同じ名前の2つの州を持つことができないようにする方法はありますか?お使いの省モデルで