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

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

    This code is stolen from previous answer and slightly simplified:

    def falsify_all_others
      Item.where('id != ?', self.id).update_all("default = 'false'")
    end
    

    You can use this method in before_save callback in your model.

    Actually, it is better to "falsify" only records which values are 'true', like this:

    Item.where('id != ? and default', self.id).update_all("default = 'false'")
    

    UPDATE: to keep code DRY, use self.class instead of Item:

    self.class.where('id != ? and default', self.id).update_all("default = 'false'")
    

提交回复
热议问题