2014-06-30 44 views
1

我在我的Ruby on Rails應用程序以下型號:如何總結Ruby on Rails中連接表中的所有關聯記錄?

class Invoice < ActiveRecord::Base 

    has_many :allocations 
    has_many :payments, :through => :allocations 

end 

class Allocation < ActiveRecord::Base 

    belongs_to :invoice 
    belongs_to :payment 

end 

class Payment < ActiveRecord::Base 

    has_many :allocations, :dependent => :destroy 
    has_many :invoices, :through => :allocations 

end 

我的問題是,在Allocation類,我想用所有相關發票的total_amount,理想情況下在before_save回撥。

這現在是不可能的,但是,因爲在當時的allocation對象會保存它僅與一個特別invoice對象相關聯。

這怎麼能以最小的數據庫查詢來完成?

+0

任何特定的' 「分配」只與一個「發票」關聯。這聽起來像你實際上希望'Invoice'有你的'total_amount'方法,這實際上非常簡單。 – coreyward

回答

3
Invoice.where(asdfasdfasdf).map(&:allocations).flatten.map(&:total_amount).compact.inject(:+) 

因爲這是rails,所以數據庫調用什麼都不是。綜上所述數字陣列您可以使用此:

ary = [0,12,2,6,nil] 
ary.compact.inject(:+) 
#=> 20 

你可以稍微打掃一下:

class Invoice 
#... 
    def total_amount 
    allocations.map(&:total_amount).inject(:+) #throws error if there is 1 nil 'total_amount data' value 
    end 

    def self.sum_allocation_amounts(sql) 
    where(sql).map(&:total_amount).inject(:+) 
    end 

end 

它不可能叫​​發票類方法中沒有錯誤,所以我傳遞一些基本的SQL作爲解決方法。理想的情況是我會做,可以直接調用ActiveRecord的地方發票調用的菊花鏈這種方式,但不工作了,我現在(「未定義的方法圖」類」)

Invoice.sum_allocation_amounts("democol = 'demo params'") 
+0

非常感謝! – Tintin81

相關問題