Validation 验证嵌套模型参数的唯一性

Validation 验证嵌套模型参数的唯一性,validation,ruby-on-rails-4,nested-forms,Validation,Ruby On Rails 4,Nested Forms,我有三种型号: class User < ActiveRecord::Base has_many :user_countries accepts_nested_attributes_for :user_countries, reject_if: :all_blank validate :user_countries end class UserCountry < ActiveRecord::Base belongs_to :user belongs_to :co

我有三种型号:

class User < ActiveRecord::Base
  has_many :user_countries
  accepts_nested_attributes_for :user_countries, reject_if: :all_blank
  validate :user_countries
end

class UserCountry < ActiveRecord::Base
  belongs_to :user
  belongs_to :country
end

class Country < ActiveRecord::Base
  has_many :user_countries
  has_many :users, :through => :user_countries
end

user\u国家/地区
型号中尝试此操作

class UserCountry < ActiveRecord::Base
  belongs_to :user
  belongs_to :country
  validates_uniqueness_of :user_id, scope: :country_id, allow_blank: false
end

谢谢!尽管正在引发ActiveRecord::RecordNotUnique异常。。我如何拯救它?我已经添加了userCountry中的validates\u唯一性\u。。。
class UserCountry < ActiveRecord::Base
  belongs_to :user
  belongs_to :country
  validates_uniqueness_of :user_id, scope: :country_id, allow_blank: false
end
add_index :user_countries, [ :user_id, :country_id ], :unique => true