【问题标题】:Validate uniqueness nested model params验证唯一性嵌套模型参数
【发布时间】:2015-08-25 13:14:26
【问题描述】:

我有三个模型:

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}

【问题讨论】:

    标签: validation ruby-on-rails-4 nested-forms


    【解决方案1】:

    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
    

    【讨论】:

    • 非常感谢!虽然它引发了 ActiveRecord::RecordNotUnique Exception.. 我如何拯救它?我在 userCountry 添加了 validates_uniqueness_of...
    猜你喜欢
    • 2014-09-20
    • 1970-01-01
    • 2012-12-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-06
    • 1970-01-01
    相关资源
    最近更新 更多