我在我的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
對象相關聯。
這怎麼能以最小的數據庫查詢來完成?
任何特定的' 「分配」只與一個「發票」關聯。這聽起來像你實際上希望'Invoice'有你的'total_amount'方法,這實際上非常簡單。 – coreyward