轨道Mongoid模型/视图计算



我需要通过几个模型的视图进行一些计算。 例:

class Teacher
  include Mongoid::Document
  has_many :students
end
class Student
  include Mongoid::Document
  belogns_to :teacher
  field gold_stars, type: Integer
  field silver_stars, type: Integer
  field bronze_stars, type: Integer
end

假设在老师看来,我需要汇总gold_stars、silver_stars和bronze_stars的数量。 聚合视图中的值的最干净方法是什么? 我猜我会使用after_update回调,但我不确定是否有更好的方法。

更新

我想要的是让老师显示他所有学生总共有多少颗金星,然后是银星,然后是铜星。

这是解决方案

teacher = Teacher.first
gold_stars = Student.where(:teacher_id => teacher.id).sum(:gold_stars)
silver_stars = Student.where(:teacher_id => teacher.id).sum(:silver_stars)
bronze_stars = Student.where(:teacher_id => teacher.id).sum(:bronze_stars)

最新更新