Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails custom validation - Only one record can be true

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 
like image 765
raphael_turtle Avatar asked Oct 24 '13 19:10

raphael_turtle


1 Answers

I think you can just check the uniqueness of active_game when it is true.

validates_uniqueness_of :active_game, if: :active_game

like image 178
onurozgurozkan Avatar answered Oct 05 '22 23:10

onurozgurozkan