2013-10-19 49 views
1

我有一個名爲Appointment的模型,它與Invoicehas_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 

執行檢查但這並不真的似乎是一個很好的選擇,因爲它真的很慢。

你能給我一些幫助嗎?

回答

0

我想這可能會幫助您:

Appointment.select("appointments.*, sum(invoice.amount) invoices_total") 
      .joins(:invoices) 
      .group(:appointment_id) 
      .having('invoices_total >= (appointment.grant_total/2)')