1

Doctor & 환자와 같은 두 모델이 있습니다.자식 모델의 부모 모델 레코드 합계 방법

Doctor model has many patients 
Patients belongs to one doctor. 

각 의사는 의사의 수수료를 저장하는 것입니다 fees(integer datatype)라는 열이 있습니다. 각 의사는 10 $, 20 $ 등의 고정 수수료가 있습니다.

이제 모든 환자의 총 요금을 계산하고 싶습니다. 예를 들어 3 명의 환자가있는 경우 3 명의 의사에게 10, 20 & 30의 요금이 부과됩니다. 그러면 모든 환자의 총 비용은 10 + 20 + 30 = 60이 될 것입니다. 레일 코드를 반복하지 않고도 SQL을 수행 할 수있는 방법은 무엇입니까?

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

class Patient < ActiveRecord::Base 
    belongs_to: doctor 
end 

답변

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 
+0

감사합니다. 쿼리를 실행하면 좋은가요? – loganathan

+0

@loganathan try'Doctor.joins (: patients) .select ("sum (doctors.fees)")'. –

+0

나는 이것을 이미 시도했지만 nil 값을 가진 의사 관계 배열을 가지고있다. => # ]> – loganathan

관련 문제