Rails 3 app model how ensure only one boolean field set to true at a time

后端 未结 8 835
误落风尘
误落风尘 2021-01-31 11:37

I have a Logo model that has fields of name:string, default:boolean. I want the true value to be unique, so that only one item in the database can be set to true at once. How do

8条回答
  •  盖世英雄少女心
    2021-01-31 12:13

    If you're coming here in a more recent time and are using Rails 6, this should be covered on the database level as well as the model level:

    db level:

    add_index :items, :default, unique: true, where: '(default IS TRUE)', algorithm: :concurrently
    

    model level:

    class Item < ApplicationRecord
      scope :default, -> { where(default: true) }
    
      validates :default, uniqueness: { conditions: -> { default } }
    end
    

提交回复
热议问题