验证唯一性嵌套模型参数

Validate uniqueness nested model params

我有三个模型:

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_countries。我如何在服务器中验证 user_countries 中 country_id 的唯一性。一个用户有很多国家:法国,​​美国...但不是例如:法国和法国。

我已将此添加到 user_countries.. 但它不起作用:

validates :user_id, uniqueness: {scope: :country_id, allow_blank: false}

user_country 模型中试试这个。

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