I don't know about the history, but I can explain how modern ratings work. The short answer is that the company Nielsen Ratings searches for a representative sample of the population, and then they offer them money to install survey equipment onto their media. The duration of the survey varies. The survey equipment records the viewing and listening habits by listening in on an identification tone inaudible to humans. The info is either transmitted electronically or a person comes by to collect it. If you want more detai I can go a bit further, but it's pretty dry stuff.
As an aside, I'm pretty interested in how Nielsen have such a dominant position in ratings. They seem to have zero competition, was it always so?