diff --git a/app/models/mat.rb b/app/models/mat.rb index 1232dd7..4d36353 100644 --- a/app/models/mat.rb +++ b/app/models/mat.rb @@ -2,10 +2,26 @@ class Mat < ActiveRecord::Base belongs_to :tournament has_many :matches + before_destroy do + if tournament.matches.size > 0 + tournament.resetMats + matsToAssign = tournament.mats.select{|m| m.id != self.id} + tournament.assignMats(matsToAssign) + end + end + + after_create do + if tournament.matches.size > 0 + tournament.resetMats + matsToAssign = tournament.mats + tournament.assignMats(matsToAssign) + end + end + def assignNextMatch - t_matches = tournament.matches.where(mat_id: nil) + t_matches = tournament.matches.select{|m| m.mat_id == nil} if t_matches.size > 0 - match = t_matches.order(:bout_number).first + match = t_matches.sort_by{|m| m.bout_number}.first match.mat_id = self.id match.save end diff --git a/app/models/tournament.rb b/app/models/tournament.rb index f0ade0a..082c9f8 100644 --- a/app/models/tournament.rb +++ b/app/models/tournament.rb @@ -9,6 +9,8 @@ class Tournament < ActiveRecord::Base has_many :wrestlers, through: :weights has_many :matches, dependent: :destroy + + def tournament_types ["Pool to bracket"] end @@ -42,14 +44,29 @@ class Tournament < ActiveRecord::Base end def assignFirstMatchesToMats - until mats.order(:id).last.matches.count == 4 - mats.order(:id).each do |m| - m.assignNextMatch - end - end + assignMats(mats) end def totalRounds self.matches.sort_by{|m| m.round}.last.round end + + def assignMats(matsToAssign) + if matsToAssign.count > 0 + until matsToAssign.sort_by{|m| m.id}.last.matches.count == 4 + matsToAssign.sort_by{|m| m.id}.each do |m| + m.assignNextMatch + end + end + end + end + + def resetMats + matchesToReset = matches.select{|m| m.finished != 1 && m.mat_id != nil} + # matchesToReset.update_all( {:mat_id => nil } ) + matchesToReset.each do |m| + m.mat_id = nil + m.save + end + end end