Finished replacing activerecord with SQL