Ich erstelle eine Rails-Migration für Provinzen und Länder. Die Idee ist, dass wir für jedes Land nicht mehr als eine Provinz mit dem gleichen Namen zulassen dürfen.
Meine create_provinces Migration ist:Eindeutigkeit mit has_many on Rails-Migration (ohne durch)
class CreateProvinces < ActiveRecord::Migration
def change
create_table :provinces do |t|
t.string :name
t.references :country, index: true, foreign_key: true
end
end
Mein country.rb ist:
class Country < ActiveRecord::Base
has_many :provinces, :uniq => true
end
Mein province.rb ist:
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
Mit :uniq => true
in country.rb, ich bin Den Fehler erhalten, der besagt: uniq ist kein bekannter Schlüssel. Beachten Sie, dass ich auch through
nicht nach anderen Fragen verwende. Gibt es eine Möglichkeit sicherzustellen, dass jedes Land nicht zwei Provinzen mit demselben Namen haben kann?