我的迁移文件中有以下内容
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
我想确保如果指定一个product_id,它是唯一的,但我也想允许null,所以我在我的模型中有以下内容:
validates :product_id,:uniqueness => true,:allow_nil => true
add_index :payment_agreements,:product_id,:unique => true
显然,当为product_id插入两个空值时,这将抛出异常.我可以简单地省略迁移中的索引,但是我有机会获得两个相同product_id的PaymentAgreements,如下所示:Concurrency and integrity
我的问题是处理这个问题的最好/最常用的方法是什么
解决方法
这取决于您的数据库服务器.
至于MysqL:
至于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.