我有一个名为的模型Appointment
,它has_many :invoices
与Invoice
.
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
但这似乎并不是一个好的选择,因为它真的很慢。
你能给我一些帮助吗?