Rails Mongoid模型/视图计算

时间:2012-10-05 01:51:57

标签: 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, type: Integer
end

让我们说教师的观点我需要汇总gold_stars,silver_stars和bronze_stars的数量。在视图中聚合值的最简洁方法是什么?我猜我会使用after_update回调,但我不确定是否有更好的方法。

更新

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

1 个答案:

答案 0 :(得分:1)

这是解决方案

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)