2016-03-04 142 views
0

我有兩個型號:Rails的ActiveRecord的查詢

class Invoice < ActiveRecord::Base 
    has_many :payments_received 
end 

class PaymentReceived < ActiveRecord::Base 
    belongs_to :invoice 
end 

我需要編寫一個查詢發現,有或者沒有payments_received或payments_received.amount的總和小於invoice.amount發票

我能找到沒有payments_received發票:

@invoices = Invoice.includes(:payments_received).where(:payments_received => { :invoice_id => nil }) 

但我需要找到發票,所有與其相關的payments_received的總和小於invoice.amo UNT。

這是一個完成我所需要的類的方法,但是我希望在不將所有發票從數據庫中提取出來並遍歷每個發票的情況下執行此操作。

def self.unpaid 
    unpaid_invoices = [] 
    total_payments = 0 
    invoices = Invoice.all 
    invoices.each do |invoice| 
    if invoice.payments_received.empty? 
     unpaid_invoices << invoice 
    else 
     invoice.payments_received.each do |payment_received| 
     total_payments += payment_received.amount 
     end 
     if total_payments < invoice.amount 
     unpaid_invoices << invoice 
     end 
    end 
    end 
    unpaid_invoices 
end 

回答

0

你可以鏈where子句:

@invoices = Invoice.includes(:payments_received).where(:payments_received => { :invoice_id => nil }).where("payments_received.amount > ?", amount) 

嘗試單獨和你得到你想要一起返回鏈查詢後什麼寫他們。

0

我希望你想要這樣的東西。

@invoices.collect do |invoice| 
    invoice.payments_received.pluck(:amount).sum < invoice.amount ? invoice : next 
end.compact 
+0

我喜歡這個代碼@Ahsan Ellahi,但我正在尋找一種方式來做到這一點,而不將所有發票的從數據庫中,並通過他們中的每一個迭代。 – brainburn