我试图通过在数据库中而不是在应用程序层中工作来提高我的应用程序的效率,我想知道我是否可以将这个计算移到数据库中。
楷模:
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
我想做的是计算报价的价格。目前我在 Offer 类中有一个 price 方法:
def price
self.lines.inject(0) do |total, line|
total + line.quantity * line.item.price
end
end
我怀疑可能可以进行Offer.sum
计算,而不是直接从数据库中获取答案,而不是遍历记录,但是ActiveRecord 查询指南的计算部分没有足够的细节来帮助我。有人吗?
谢谢!