2012-01-07 58 views
3

我試圖通過在數據庫中而不是在應用層中工作來提高我的應用程序的效率,並且我想知道是否可以將此計算移入數據庫。我可以將這個軌道計算推入數據庫嗎?

型號:

class Offer < ActiveRecord::Base 
    has_many :lines 
    has_many :items, :through => :lines 
end 

class Line < ActiveRecord::Base 
    belongs_to :offer 
    belongs_to :item 
    # also has a 'quantity' attribute (integer) 
end 

class Item < ActiveRecord::Base 
    has_many :lines 
    has_many :offers, :through => :lines 
    # also has a 'price' attribute (decimal) 
end 

我想要做的是計算報價的價格。目前,我有在發售類價格法:

def price 
    self.lines.inject(0) do |total, line| 
    total + line.quantity * line.item.price 
    end 
end 

我懷疑它可能做一個Offer.sum計算而不是將直接從數據庫中得到答案,而不是通過記錄循環,但Calculations section of the ActiveRecord query guide沒有按沒有足夠的細節來幫助我。任何人?

謝謝!

回答

3

你是對的,你可以用sum做到這一點。類似這樣的:

class Offer < ActiveRecord::Base 
    # ... 

    def price 
    self.lines.sum 'lines.quantity * items.price', :joins => :item 
    end 
end 

當你打電話給Offer.find(some_id).price上面將構造一個像這樣的查詢:

SELECT SUM(lines.quantity * items.price) AS total 
    FROM lines 
    INNER JOIN items ON items.id = lines.item_id 
    WHERE lines.offer_id = <some_id> 
; 
2

有時候你最好用SQL。

SELECT SUM(lines.quantity * items.price) AS total 
    FROM offers 
    INNER JOIN lines ON offers.id = lines.offer_id 
    INNER JOIN items ON items.id = lines.item_id 
    WHERE offers.id = 1 
; 
相關問題