1

I need to do some calculation through a view on a few models. Example:

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

Let's say on the Teacher's view I need to aggregate the number of gold_stars, silver_stars and bronze_stars. What is the cleanest way to aggregate the values in the view? I'm guessing I would use a after_update callback but I'm not sure if there is a nicer way.

UPDATE

What I want is for the Teacher to display how many gold stars all his students have in total, then silver, then bronze.

GTDev
  • 5,488
  • 9
  • 49
  • 84
  • you want to aggregate number of stars for all the students belongs_to a teacher or total stars of students?? – abhas Oct 05 '12 at 04:06

1 Answers1

1

here is the solution

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)
abhas
  • 5,193
  • 1
  • 32
  • 56
  • Elegant I like thanks. Do you think this belongs in a virtual attribute on Teacher class? – GTDev Oct 05 '12 at 05:51