【问题标题】:Rails Mongoid model/view calculationRails Mongoid 模型/视图计算
【发布时间】:2012-09-26 03:35:23
【问题描述】:

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

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 和 brown_stars 的数量。聚合视图中的值的最简洁方法是什么?我猜我会使用 after_update 回调,但我不确定是否有更好的方法。

更新

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

【问题讨论】:

  • 您要汇总所有学生所属_老师的星数还是学生的总星数??

标签: ruby-on-rails-3 model views mongoid document-database


【解决方案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)

【讨论】:

  • 优雅我喜欢谢谢。你认为这属于 Teacher 类的虚拟属性吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-01-07
  • 2015-09-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多