我已经在我的迁移文件以下为NULL列DB唯一索引Rails的唯一性约束和匹配
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它是独一无二的,但我也希望允许空,因此我已经在我的模型如下:
validates :product_id,
:uniqueness => true,
:allow_nil => true
伟大的作品,但后来我应该添加一个索引来迁移文件
add_index :payment_agreements, :product_id, :unique => true
很明显,当为product_id插入两个空值时,这将引发异常。我只是简单地忽略了迁移索引,但然后有机会得到两个支付协议,具有相同的product_id,如下所示:Concurrency and integrity
我的问题是处理这个问题的最佳/最常见的方式是什么问题
这个问题是类似于http://stackoverflow.com/questions/191421/how-to-create-a-unique-index-on-a-null-column – x1a4 2010-05-28 05:30:06
validates_uniqueness_of:PRODUCT_ID,:如果= > lambda {!self.product_id.nil? } – user386660 2010-07-09 10:11:20