加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – Rails唯一性约束,并为null列匹配db唯一索引

发布时间:2020-12-16 20:07:03 所属栏目:百科 来源:网络整理
导读:我的迁移文件中有以下内容 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.timestam
我的迁移文件中有以下内容
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:

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.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读