简体   繁体   English

在nil值上进行Rails唯一性验证

[英]Rails uniqueness validation on nil values

I have a rails model that has attributes 'term' and 'section'. 我有一个Rails模型,其属性为“ term”和“ section”。 I want a uniqueness constraint on these attributes, so I tried this: 我想要这些属性的唯一性约束,所以我尝试了以下方法:

validates_uniqueness_of :term, scope: :section

This would only work when both 'term' and 'scope' were not nil, but I want the constraint to still apply when there are nil values. 这仅在'term'和'scope'都不为零时才有效,但是我希望在有nil值时约束仍然适用。 Looking at the ActiveRecord::Validations docs , I saw that setting 'allow_nil' to false would prevent the skipping of validation when an a value is nil. 查看ActiveRecord :: Validations 文档 ,我看到将'allow_nil'设置为false可以防止在值为nil时跳过验证。 But the default value for this option is already false. 但是此选项的默认值已经为false。

I tried setting allow_nil to both false and true anyways, but there was no change in behavior. 无论如何,我都尝试将allow_nil设置为false和true,但是行为没有变化。 Does anyone know why I cannot get the validation to work when there are nil values? 有谁知道为什么在没有值的情况下我无法使验证工作?

您可以添加

validates_presence_of :term, :section

"I want the unique constraint to be on the combination of term and section. I don't want a unique constraint on them individually." “我希望唯一的约束条件是术语和部分的组合。我不想单独地对它们进行唯一约束。”

That's cross-field validation; 那就是跨领域验证; you'll need to build a custom validator (using validates_with). 您需要构建一个自定义验证器(使用validates_with)。 Read about that here. 在这里阅读。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM