Ruby on rails 3 Rails Mongoid模型/视图计算

Ruby on rails 3 Rails Mongoid模型/视图计算,ruby-on-rails-3,model,views,mongoid,document-database,Ruby On Rails 3,Model,Views,Mongoid,Document Database,我需要通过几个模型的视图进行一些计算。例如: 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, t

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

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
假设根据老师的观点,我需要将金星、银星和铜星的数量相加。聚合视图中的值的最干净的方法是什么?我猜我会使用更新后回调,但我不确定是否有更好的方法

更新

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

这是解决方案

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)
这是解决办法

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)

您想为所有学生合计一名教师的星星数或学生的星星总数??您想为所有学生合计一名教师的星星数或学生的星星总数??优雅我喜欢谢谢。你认为这属于教师课堂上的虚拟属性吗?优雅我喜欢谢谢。你认为这属于教师课堂上的虚拟属性吗?