0

我有两个活动记录StudentDemographics,并且StudentWeeklyReport都有这样的has_many关系:

class StudentDemographics < ActiveRecord::Base
  has_many :student_weekly_reports, :foreign_key => :student_id
end

我必须在最后一个第五周的研讨会上检查每个学生的分数和最新的一个。如果结果是true,学生应该是活跃的,否则是不活跃的。我有以下代码。在这里,我在每个日期重复循环。@distinct是一个日期数组。

 for i in 0...@distinct.length
     active = 0
     inactive = 0
     sum = safe.length
     @students = StudentDemographics.where("date <= ?", @distinct[i]).select("student_id") - safe
     @students.each do |student|
        @stu = StudentWeeklyReport.where(:student_id => student.student_id).select("student_id,golden_eggs").last(5)
            if @stu.length > 4
                if @stu[4].golden_eggs > @stu[0].golden_eggs
                  safe << student
                  active += 1
                else
                  inactive += 1
                end
            else
                safe << student
                active += 1
            end
      end
      @active[i] = active + sum
      @inactive[i] = inactive
end

表现并不好。这需要超过 3 秒的时间。我的 mysql 数据库在表中有 13600,在StudentWeeklyReports表中有 2000 StudentDemographics。谁能建议如何优化以下代码?

4

2 回答 2

1
     @students = StudentDemographics.includes(:student_weekly_reports) - safe
 for i in 0...@distinct.length
     active = inactive = 0
     @students.each do |student|
        next if student.date > @distinct[i]
        @stu = student.student_weekly_reports.select("golden_eggs").last(5)
            if @stu.length > 4 && (@stu[4].golden_eggs <= @stu[0].golden_eggs)
                inactive += 1
            else
                safe << student
                active += 1
            end
      end
      @active[i] = active + safe.length
      @inactive[i] = inactive
end
于 2013-10-22T08:09:32.223 回答
0
@students = StudentDemographics.includes(:student_weekly_reports).where("date <= ?", @distinct.min).select("student_id")
# The above line will fetch all the necessary records you require 

for i in 0...@distinct.length
 active = inactive = 0
 @students = @student.select { |student_demographics| student_demographics.date <= @distinct[i] } - safe
 @students.each do |student|
   @stu = student.student_weekly_reports.select("golden_eggs").last(5)
   if @stu.length > 4 and (@stu[4].golden_eggs <= @stu[0].golden_eggs)
     inactive += 1
   else
     safe << student
     active += 1
   end
  end
  @active[i] = active + safe.length
  @inactive[i] = inactive
end
于 2013-10-22T11:10:46.607 回答