mercredi 20 juillet 2016

Uniqueness with has_many on Rails migration (without through)

I am creating a Rails migration for provinces and countries. The idea is that for each country, we can't allow more than one province with the same name.
My create_provinces migration is:

class CreateProvinces < ActiveRecord::Migration
def change
    create_table :provinces do |t|
      t.string :name
      t.references :country, index: true, foreign_key: true
    end
end


My country.rb is:

class Country < ActiveRecord::Base
  has_many :provinces, :uniq => true
end

My province.rb is:

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

With :uniq => true in country.rb, I am getting the error that says :uniq is not a known key. Note that I also am not using through as per other questions. Is there a way to make sure each country can't have two provinces with the same name?

Aucun commentaire:

Enregistrer un commentaire