You can use association callback.
has_many :teams, :through => :team_matches, :source => :team, :before_add => :limit_number_of_teams
def limit_number_of_teams(added_team)
raise Exception.new('Team limit for the match reached') if teams.size >= 2
end