我試圖通過在數據庫中而不是在應用層中工作來提高我的應用程序的效率,並且我想知道是否可以將此計算移入數據庫。我可以將這個軌道計算推入數據庫嗎?
型號:
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沒有按沒有足夠的細節來幫助我。任何人?
謝謝!