replace some raw sql with database-agnostic activerecord queries