Ruby-on-rails Rails:验证两列的唯一性(一起)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34424154/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 00:20:21  来源:igfitidea点击:

Rails: validate uniqueness of two columns (together)

ruby-on-railsruby-on-rails-3ruby-on-rails-4activerecordrails-activerecord

提问by Hymanson Cunningham

I have a Releasemodel with mediumand countrycolumns (among others). There should not be releasesthat share identical medium/countrycombinations.

我有一个Release带有mediumcountry列的模型(等等)。不应该releases有相同的medium/country组合。

How would I write this as a rails validation?

我将如何将其编写为 Rails 验证?

回答by tompave

You can use a uniquenessvalidation with the scopeoption.

您可以使用该选项的唯一性验证scope

Also, you should add a unique index to the DB to prevent new records from passing the validations when checked at the same time before being written:

此外,您应该向数据库添加一个唯一索引,以防止新记录在写入之前同时检查时通过验证:

class AddUniqueIndexToReleases < ActiveRecord::Migration
  def change
    add_index :releases, [:country, :medium], unique: true
  end
end



class Release < ActiveRecord::Base
  validates :country, uniqueness: { scope: :medium }
end

回答by Aamir

All the above answers are missing how to validate the uniqueness of multiple attributes in a model. The code below intends to tell how to use multiple attributes in a scope.

以上所有答案都缺少如何验证模型中多个属性的唯一性。下面的代码旨在说明如何在一个范围内使用多个属性。

validates :country, uniqueness: { scope: [:medium, :another_medium] }

It validates uniqueness of countryin all rows with values of mediumand another_medium.

这验证了独特的country与值的所有行mediumanother_medium

Note:Don't forget to add an index on the above column, this insures fast retrieval and adds a DB level validation for unique records.

注意:不要忘记在上面的列上添加索引,这可以确保快速检索并为唯一记录添加数据库级别的验证。

回答by K M Rakibul Islam

You can pass a :scopeparameter to your validator like this:

您可以:scope像这样将参数传递给验证器:

validates_uniqueness_of :medium, scope: :country

See the documentationfor some more examples.

有关更多示例,请参阅文档