Move logic out of ruby and into sql