Rails uniqueness constraint and matching db unique index for null column

Posted by Dave on Stack Overflow See other posts from Stack Overflow or by Dave
Published on 2010-05-28T05:15:25Z Indexed on 2010/05/28 5:21 UTC
Read the original article Hit count: 382

I have the following in my migration file

  def self.up
    create_table :payment_agreements do |t|
      t.boolean    :automatic, :default => true, :null => false
      t.string     :payment_trigger_on_order
      t.references :supplier
      t.references :seller
      t.references :product
      t.timestamps
    end
  end

I want to ensure that if a product_id is specified it is unique but I also want to allow null so I have the following in my model:

  validates :product_id,
            :uniqueness => true,
            :allow_nil => true

Works great but I should then add an index to the migration file

add_index :payment_agreements, :product_id, :unique => true

Obviously this will throw an exception when two null values are inserted for product_id. I could just simply omit the index in the migration but then there's the chance that I'll get two PaymentAgreements with the same product_id as shown here: Concurrency and integrity

My question is what is the best/most common way to deal with this problem

© Stack Overflow or respective owner

Related posts about ruby-on-rails

Related posts about migration