と関連付けられAppointmentているという名前のモデルがあります。has_many :invoicesInvoice
Appointmentにもgrand_totalbigdecimal フィールドInvoiceがあり、amountbigdecimal フィールドがあります。
というクエリを作成したいと思いますselect all Appointments whose invoices' amounts sum is greater or equal to 50% of grand_total。
実際には、すべての予定を選択し、それらをループして、次のようにそのチェックを実行します
@selected_appointments = []
Appointments.all.each do |appointment|
invoices_sum = BigDecimal.new(0)
appointment.invoices.each do |invoice|
invoices_sum += invoice.amount
end
if invoices_sum >= (appointment.grant_total/2)
@selected_appointments.push(appointment)
end
end
しかし、これは非常に遅いため、実際には良いオプションではないようです。
助けてもらえますか?