私はアプリケーション層ではなくデータベースで作業をすることでアプリケーションの効率を上げようとしています。この計算をデータベースに移すことができるかどうかは疑問です。このレール計算をデータベースにプッシュできますか?
モデル:
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
計算を行うことも可能である疑いがあるというレコードをループするよりも、DBから直接答えを得るだろうが、Calculations section of the ActiveRecord query guideのdoesn:現在、私は価格のオファークラスのメソッドを持っています私を助けるのに十分な詳細がありません。誰ですか?
ありがとうございます!