ruby-on-rails - 如何从子模型中总结父模型记录

标签 ruby-on-rails postgresql ruby-on-rails-4 rails-activerecord

我有两个模型,例如 Doctor & Patient。

Doctor model has many patients
Patients belongs to one doctor.

每个医生都有名为fees(integer datatype) 的列,用于存储医生费用。每个医生都有固定的费用,如 10 美元、20 美元等。

现在我想计算所有患者的总费用。例如,如果有 3 名患者和 3 名医生,费用分别为 10、20 和 30。那么所有患者的总费用将为 10+20+30 = 60。他们是否有任何方法可以在不在 Rails 代码中循环的情况下使用 sql?

class Doctor < ActiveRecord::Base
  has many :patients
end

class Patient < ActiveRecord::Base
  belongs_to: doctor
end

最佳答案

做如下:-

# get first all doctors
doctors = Doctor.all
total_fees = doctors.inject(0) do |sum, doctor|
  # doctor.patients.count will give how many patients visited 
  # that specific doctor. With that count, I am multiplying that specific
  # doctor's fees, which is giving each doctors earnings from all his 
  # patients. # inject block then summing all doctors earnings and returned back.
  sum += doctor.fees * doctor.patients.size
end
total_fees
# => 60

如果你喜欢一个类轮 -

doctors.inject(0) { |sum, doctor| sum + doctor.fees * doctor.patients.size }

再次阅读帖子后,我想出了以下解决方案(与上面相同,但没有循环):-

Doctor.joins(:patients).select("sum(doctors.fees) as total")[0].total # => 60

这是另一种更有效的方法:-

Doctor.joins(:patients).sum("doctors.fees") # => 60

关于ruby-on-rails - 如何从子模型中总结父模型记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26687129/

相关文章:

ruby-on-rails - 有没有办法在不失去调试和开发代码的能力的情况下在 Rails 中获得良好的性能?

postgresql - 为什么查询计划如此不同?

java - 无法获取 PSQLException 的错误消息

ruby - 解析 DST 中的时区缩写

ruby-on-rails - PG 数据库在 localhost 上运行良好,但在 heroku 上运行不佳

ruby-on-rails - 将参数传递给 Rails 中的自定义 RESTful 路由(使用 :collection)

ruby-on-rails - Rails 4 传输响应

postgresql - 触发与检查约束

ruby-on-rails - 如何在FactoryGirl中处理外键

ruby-on-rails - 为什么 Awesome Print 在某些 Rails 集合对象上不起作用?