Rails uniqueness constraint and matching db unique index for null column

那年仲夏 提交于 2019-12-03 23:03:14

it depends on your db server. as for mysql:

A UNIQUE index creates a constraint such that all values in the index must be distinct. An error occurs if you try to add a new row with a key value that matches an existing row. This constraint does not apply to NULL values except for the BDB storage engine. For other engines, a UNIQUE index allows multiple NULL values for columns that can contain NULL.

Some major database systems do not allow a unique index to contain multiple NULLs: unique applies to NULLs as well as non-NULLs. There are ways around this on the database level (e.g., triggers, or a computed column; see link text).

You could address this on an application level and put in a validation that checks for uniqueness if the product_id is not null.

validate :enforce_unique_product_id
def enforce_unique_product_id
  if (!self.product_id.nil? &&
      PaymentAgreement.exists?(:conditions=>['product_id = ?', self.product_id]))
    errors.add_to_base('There is already an agreement with product id " + 
                       self.product_id)
  end
end

(Update: As pointed out by zed_0xff, MySql allows multiple NULLs in a UNIQUE index in the most commonly used storage engines.)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!