Rails:共同验证两列的唯一性 [英] Rails: validate uniqueness of two columns (together)

查看:93
本文介绍了Rails:共同验证两列的唯一性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 Release 模型,其中有 medium country 列(以及其他)。不应有发行版共享相同的媒介 / 国家组合。

I have a Release model with medium and country columns (among others). There should not be releases that share identical medium/country combinations.

我将如何编写它作为Rails验证?

How would I write this as a rails validation?

推荐答案

您可以使用 scope 选项进行> uniqueness 验证。

You can use a uniqueness validation with the scope option.

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

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

这篇关于Rails:共同验证两列的唯一性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆