1

我有一个名为的模型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

但这似乎并不是一个好的选择,因为它真的很慢。

你能给我一些帮助吗?

4

1 回答 1

0

I think this might help you:

Appointment.select("appointments.*, sum(invoice.amount) invoices_total")
           .joins(:invoices)
           .group(:appointment_id)
           .having('invoices_total >= (appointment.grant_total/2)')
于 2013-10-19T19:50:46.053 回答