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

后端 未结 8 945
误落风尘
误落风尘 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:20

    In your controller code you could do something like this.... please note you're probably taking Item2 as a param[...] so you can interchange that below

    @items_to_be_falsified = Item.where('id != ?', Item2.id)
    
    @items_to_be_falsified.each do |item|
      item.default = false
      item.save
    end
    

    Please note when you get this working, its good practice to move this into the model, make it into a function and call it like Item2.falsify_all_others like below

    def falsify_all_others
      Item.where('id != ?', self.id).each do |item|
        item.default = false
        item.save
      end
    end
    

    Enjoy!

提交回复
热议问题