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 someone tries to create a new 'game' record when there is an already active game then they should get an error. Below is what I currently have but isn't working!
validate :active_game def active_game if active == true && Game.find_by(active: true) == true errors[:name] = "a game is already active!" end end
I think you can just check the uniqueness of active_game when it is true.
validates_uniqueness_of :active_game, if: :active_game
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With