简体   繁体   English

在rails中循环通过fixnum

[英]looping through a fixnum in rails

I have an examscore model with the following columns: 我有一个带有以下各列的examscore模型:

academic_year_id, grade_id, student_id, subject_id, total_score Academic_year_id,grade_id,student_id,subject_id,total_score

and an averagescore model with these columns: 以及包含以下列的averagescore模型:

academic_year_id, grade_id, student_id, average 平均学年编号,年级编号,学生编号,平均

My requirement is to iterate through the Examscore model by academic_year_id and grade_id , and calculate the average score of each student for all subjects taken by the student (ie sum total score of all subjects divided by the number of subjects) then store the average in the AverageScore model. 我的要求是通过Examscore模型按academic_year_idgrade_id进行迭代,并计算该学生修读的所有科目的每个学生的平均分数(即,所有科目的总分数除以科目数),然后将平均值存储在AverageScore模型。 I am finding this difficult and any help will be very much appreciated. 我发现这很困难,我们将不胜感激。

What I have done so far is: 到目前为止,我所做的是:

total = 0
counter = 0 
scores = Examscore.where(:academic_year_id => 3, :grade_id => 4)
scores.each do |std|
  std.student_id.each do |tot|
  total += tot.total_score 
  counter += 1
end
puts total.fdiv(counter)

but it fails because std.student_id is a Fixnum not an Array . 但是失败,因为std.student_id是一个Fixnum而不是一个Array

Any guidance on how to approach this please? 请问如何处理这个问题的任何指导?

As this is some sort of school project, I'm assuming the tables are not that big. 由于这是某种学校项目,因此我假设桌子不是很大。 Therefore, this should do the trick: 因此,这应该可以解决问题:

scores = Examscore.where(academic_year_id: 3, grade_id: 4)

scores.group_by(&:student_id).each do |student_id, examscores|
  average = examscores.sum(&:total_score) / examscores.size.to_f
  AverageScore.create academic_year_id: 3, grade_id: 4,
                      student_id: student_id, average: average
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM