Unique index allowing null values ​​in rails

I have a Message.rb that has columns A, B and C.

I added a unique index to Message like this:

add_index :messages, [:a, :b, :c], unique: true, name: 'mm_uniqueness'

      

however, I would like column A to be nullable without triggering the uniqueness constraint.

So:

original a=1, b=2, c=3
second   a=1, b=2, c=3 (not unique)

original a=null, b=2, c=3
second   a=null, b=2, c=3 (unique)

      

how to do it?

+3


source to share


1 answer


Try to create a partial index:



add_index :messages, [:a, :b, :c], unique: true, name: 'mm_uniqueness', where: 'a != null'

      

0


source







All Articles