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

我想做的是计算报价的价格。目前我在 Offer 类中有一个 price 方法:

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

我怀疑可能可以进行Offer.sum计算,而不是直接从数据库中获取答案,而不是遍历记录,但是ActiveRecord 查询指南的计算部分没有足够的细节来帮助我。有人吗?

谢谢!

4

2 回答 2

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>
;
于 2012-01-07T07:17:42.330 回答
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
;
于 2012-01-07T06:58:44.897 回答