Pergunta

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.

Foi útil?

Solução

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)
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top