1

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?

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.