0
我有一個Order
模型,它有很多items
,它看起來像這樣如何在軌上加載ruby的子模型的總和值?
class Order < ActiveRecord::Base
has_many :items
def total
items.sum('price * quantity')
end
end
而且我有一個訂單指數來看,查詢訂單表這樣
def index
@orders = Order.includes(:items)
end
然後,在視圖中,我訪問的訂單總額,因此,你會看到噸SUM
查詢這樣
SELECT SUM(price * quantity) FROM "items" WHERE "items"."order_id" = $1 [["order_id", 1]]
SELECT SUM(price * quantity) FROM "items" WHERE "items"."order_id" = $1 [["order_id", 2]]
SELECT SUM(price * quantity) FROM "items" WHERE "items"."order_id" = $1 [["order_id", 3]]
...
這是prett y緩慢加載order.total
一個接一個,我想知道如何通過單個查詢以熱切的方式加載總和,但我仍然可以像以前一樣訪問order.total
。