Replaced Ruby count with SQL count - significantly faster and far less memory consumed.