1
我有一個名爲Appointment
的模型,它與Invoice
有has_many :invoices
關聯。ActiveRecord查詢總結嵌套的對象值並與父模型進行比較
Appointment
也有一個grand_total
bigdecimal字段,而Invoice
有一個amount
bigdecimal字段。
我想創建一個查詢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
執行檢查但這並不真的似乎是一個很好的選擇,因爲它真的很慢。
你能給我一些幫助嗎?