如何获取关联模型对象的总和

时间:2014-10-11 15:44:34

标签: ruby-on-rails model-associations

class AssessmentScore < ActiveRecord::Base
  belongs_to :student
  belongs_to :exam
  belongs_to :exam_group
  belongs_to :ca_criteria
end

class CaCriteria < ActiveRecord::Base
  has_many    :assessment_scores
  belongs_to :ca_group

  validates_numericality_of :max_marks
end

我尝试运行以下代码片段:

ca_scores = {}
AssessmentScore.find(:all,
  :conditions=>["exam_id IN (1,2,3) AND ca_criteria_id IS NOT NULL"],
  :include=>:ca_criteria
).group_by(&:exam_id).each do |e_id, v|
  ca_scores[e_id] = {}
  v.group_by(&:student_id).each{|s_id, v2|
    ca_scores[e_id][s_id] = {:score=>v2.sum(&:grade_points), :max_marks=>v2.ca_criteria.sum(&:max_marks)}
  }
end

当我运行上面的代码时,我收到以下错误:

  

reportsController#create_reports中的NoMethodError

     

undefined method`ca_criteria&#39;

这就是我的工作方式:

  ca_scores = {}
  AssessmentScore.find(:all,
    :conditions=>["exam_id IN (1,2,3) AND ca_criteria_id IS NOT NULL"],
    :include=>:ca_criteria
  ).group_by(&:exam_id).each do |e_id, v|
    ca_scores[e_id] = {}
    max_marks = 0
    v.group_by(&:student_id).each{|s_id, v2|
      v2.each{|v3|
        max_marks += v3.ca_criteria['max_marks']
      }
      ca_scores[e_id][s_id] = {:score=>v2.sum(&:grade_points), :max_marks=>max_marks}
    }
  end

我很好奇,这是编写下面代码的无错误方法:

:max_marks=>v2.ca_criteria.sum(&:max_marks)

0 个答案:

没有答案