添加不在 id/foreign_key 上的参照完整性



在 Rails 6 应用程序中,我有一个具有 3 个属性的Course模型:instructor_idyeartag

如果没有已经定义的course与同一instructor_idyear具有相同的值,如果有办法使具有tagcourse无效? 例如,使用下表courses

|instructor_id|year|tag|
|1            |2019|   |

以下陈述都是正确的

Course.new(instructor_id: 1, tag: 2019).valid? #=> true
Course.new(instructor_id: 1, tag: 2020).valid? #=> false

还是我应该为此编写一个自定义验证器?

澄清一下,这里是我的自定义验证器

class Course < ApplicationRecord
validates :tag,   referential_integrity: { reference: :year, scope: :instructor },
allow_nil: true
end

class ReferentialIntegrityValidator < ActiveModel::EachValidator
def validate_each(record, attribute, value)
record.errors.add(attribute, :required) unless record.class.find_by(options[:scope] => record.send(options[:scope]),
  options[:reference] => value)
end
end

我能否实现相同的起诉内置验证?

也许您正在寻找这样的验证或类似的年份而不是标签

validates :instructor_id, uniqueness: { scope: [:tag] }

最新更新