Rails custom validation - Only one record can be true

后端 未结 3 1484
野性不改
野性不改 2021-02-05 04:44

I\'m trying to write a validation where only one record can be true. I have a \'game\' model with an \'active\' boolean column, only one game can be active at any time, so if so

3条回答
  •  一向
    一向 (楼主)
    2021-02-05 05:09

    You also need to check against the ID if the record is already persisted. Otherwise, saving the active game again would not succeed because there is an existing active game, which happens to be itself.

    validate :only_one_active_game
    scope :active, where(:active => true)
    
    protected
    
    def only_one_active_game
      return unless active?
    
      matches = Game.active
      if persisted?
        matches = matches.where('id != ?', id)
      end
      if matches.exists?
        errors.add(:active, 'cannot have another active game')
      end
    end
    

提交回复
热议问题