It's all a fallacy. St Andrews, and several other Scottish universities, get towards the top of rankings because a lot of its students are either international or Scottish. Because Scottish students take more Highers than the average English student takes A Levels, it converts to a higher average entry grade, which has an effect on their overall ranking. That, in turn, probably attracts some people with really high A Level grades too - but only the ones willing to take 4 years doing what they could do in 3 years at a non-Scottish university and only the ones happy to study kind of in the middle of nowhere that might not necessarily be the best environment for most people.
St Andrews is only joint 25th for research quality. That's below Glasgow and Edinburgh. (note that Edinburgh also gets overrated over Glasgow, simply for being the capital city).
Confirmation bias has made people think St Andrews is better than it is. Some of its buildings are old and look pretty. So... maybe it attracts old or pretty teachers, or traditional and attractive students? Nothing directly correlates in to being objectively better as a university. There is a self-fulfilling prophecy though that because the kinds of people willing and able to spend 4 years in a small town are more likely to be quiet, studious, people, then they're more likely to get better exam results and therefore more likely to have better prospects on average. But that's really about those students, not about St Andrews itself. And then employers start to think St Andrews is special too.