0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Rails: validates: 指定した値の時だけ複数カラムでuniquenessを制約を掛ける方法備忘録

Posted at

ケース

一つのfugaに対して紐付く複数のhogeの内、is_piyoがfalseであれば幾らでも登録できるが、trueのものは一つしか登録できないようにしたい

コード

app/models/user.rb
class Hoge < ApplicationRecord
  belongs_to :fuga

  validates :is_piyo,
            inclusion: { in: [true, false] },
            uniqueness: { scope: :fuga_id,
                          conditions: -> { where(is_piyo: true) }}
end
0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?