LoginSignup
2
1

More than 5 years have passed since last update.

DB上で nil と nil は別のものとして扱われるのでRailsで対策として partial indexを使う方法

Posted at

instantstart_date, end_date の二つのどちらかにだけ値が入るモデルがあって、こんな index を作ってたんですが、

add_index :foos, [:name, :instant, :start_date, :end_date], unique: true

これではnilがDB上ではそれぞれ異なる値として処理されるために unique 制限が全く働いてくれませんでした。

対策

whereを使ってpartial indexを作り対策しましょう。

add_index :foos, [:name, :start_date, :end_date], unique: true, where: 'instant IS NULL'
add_index :foos, [:name, :instant], unique: true, where: 'start_date IS NULL and end_date IS NULL'

参考

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1