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

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

    Okay there is a few more things you will need.

    Don't use the field name default, its usually reserved for the database. Saving a record with a default as false will set all records to false, this isnt what you want. check to see if we are setting this record to true and the falseify.

      before_save :falsify_all_others
      def falsify_all_others
        if is_default
          self.class.where('id != ?', self.id).where('is_default').update_all(:is_default => false)
        end
      end
    

提交回复
热议问题