class StatisticSchoolReportTask def call School.find_each do |school| evaluate_count = Game.joins(:challenge) .joins('LEFT JOIN course_members ON course_members.user_id = games.user_id') .joins('LEFT JOIN homework_commons_shixuns hcs ON hcs.shixun_id = challenges.shixun_id') .joins('LEFT JOIN homework_commons hc ON hcs.homework_common_id = hc.id AND hc.homework_type = 4') .joins('LEFT JOIN courses ON hc.course_id = courses.id AND course_members.course_id = courses.id') .where(courses: { school_id: school.id }) .sum(:evaluate_count) report = SchoolReport.find_or_initialize_by(school_id: school.id) report.school_name = school.name report.shixun_evaluate_count = evaluate_count report.save end end end