Refactored raw SQL queries in ActiveRecord queries