2012-01-07 8 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計算を行うことも可能である疑いがあるというレコードをループするよりも、DBから直接答えを得るだろうが、Calculations section of the ActiveRecord query guideのdoesn:現在、私は価格のオファークラスのメソッドを持っています私を助けるのに十分な詳細がありません。誰ですか?

ありがとうございます!

答えて

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 
; 
関連する問題