我有两个模型,例如 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/