我有两个模型,如Doctor&患者。
Doctor model has many patients
Patients belongs to one doctor.
每位医生都有名为fees(integer datatype)
的栏目,用于存储医生费用。每位医生都有10美元,20美元等固定费用。
现在我想计算所有患者的总费用。例如,如果存在3名患者,其中3名医生收费10,20和20。分别为30。然后所有患者的总费用将是10 + 20 + 30 = 60.他们是否可以在没有在rails代码中循环的情况下执行sql?
class Doctor < ActiveRecord::Base
has many :patients
end
class Patient < ActiveRecord::Base
belongs_to: doctor
end
答案 0 :(得分:1)
执行以下操作: -
# 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