I have an Order
model, it has many items
, it looks like this
class Order < ActiveRecord::Base
has_many :items
def total
items.sum('price * quantity')
end
end
And I have an order index view, querying order table like this
def index
@orders = Order.includes(:items)
end
Then, in the view, I access total of order, as a result, you will see tons of SUM
query like this
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]]
...
It's pretty slow to load order.total
one by one, I wonder how can I load the sum in a eager manner via single query, but still I can access order.total
just like before.