3
votes

I have a rails model that has attributes 'term' and '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. 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. But the default value for this option is already false.

I tried setting allow_nil to both false and true anyways, but there was no change in behavior. Does anyone know why I cannot get the validation to work when there are nil values?

2
What's the purpose of setting :scope to :section ? - Alireza
@Ali the term must be unique for all records that have the same value for section. - Patrick Oscity
@user2745175 try to update rails or specify the version you use. Your DB version might be useful too if rails update doesn't help. I just tested your case with Rails 4.1.6 & PG 9.1 and it works as you expect. - Pavel S

2 Answers

0
votes

You can just add

validates_presence_of :term, :section
0
votes

"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). Read about that here.