验证两列的唯一性

验证两列的唯一性

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

问题描述

我有一个带有 mediumcountry 列(以及其他)的 Release 模型.不应有共享相同的 medium/country 组合的 releases.

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?

推荐答案

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

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:验证两列的唯一性(一起)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-27 21:06