我的迁移文件中有以下内容
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
Run Code Online (Sandbox Code Playgroud)
我想确保如果指定了product_id它是唯一的但我也想允许null所以我在我的模型中有以下内容:
validates :product_id,
:uniqueness => true,
:allow_nil => true
Run Code Online (Sandbox Code Playgroud)
工作得很好,但我应该为迁移文件添加一个索引
add_index :payment_agreements, :product_id, :unique => true
Run Code Online (Sandbox Code Playgroud)
显然,当为product_id插入两个空值时,这将抛出异常.我可以简单地省略迁移中的索引,但是我有可能获得两个PaymentAgreements,其中product_id与此处所示相同:并发性和完整性
我的问题是处理这个问题的最佳/最常用方法是什么
migration ruby-on-rails unique-index validates-uniqueness-of