Reputation: 11
I'd like to create a unique index for a table, consisting of 3 columns, but to check only if one of them has a specific value:
something like add_index :table, [:col1, :col2, :col3], unique: true
but only if col3 = true, otherwise I don't care about col1, col2, :col3 = false uniqueness.
is there a way to do it in a migration to keep it at the DB level, or can I only validate this case in the model?
Upvotes: 1
Views: 483
Reputation: 875
I don't believe you can have conditional uniqueness constraints at the database layer (via migrations). You can add this as a conditional validation at the AR layer though which should be sufficient for your purposes (though it should be noted this can introduce some race conditions). ie.
validates [:col1, :col2], uniqueness: true, if: ":col3 == true"
Hope that helps.
Upvotes: 2