Performance improvements for ordergroup.update_stats!

As I have learned today. Let mysql do the counting, calculation stuff.
In most of the cases, it will be much faster!
This commit is contained in:
benni 2012-12-16 13:48:15 +01:00
parent 8074fedefd
commit b86172bc62
2 changed files with 6 additions and 3 deletions

View file

@ -28,7 +28,7 @@ class Order < ActiveRecord::Base
# Finders
scope :open, where(state: 'open').order('ends DESC')
scope :finished, where("state = 'finished' OR state = 'closed'").order('ends DESC')
scope :finished, where("orders.state = 'finished' OR orders.state = 'closed'").order('ends DESC')
scope :finished_not_closed, where(state: 'finished').order('ends DESC')
scope :closed, where(state: 'closed').order('ends DESC')
scope :stockit, where(supplier_id: 0).order('ends DESC')

View file

@ -57,8 +57,11 @@ class Ordergroup < Group
def update_stats!
time = 6.month.ago
jobs = users.collect { |u| u.tasks.done.sum('duration', :conditions => ["updated_on > ?", time]) }.sum
orders_sum = group_orders.select { |go| !go.order.ends.nil? && go.order.ends > time }.collect(&:price).sum
# Get hours for every job of each user in period
jobs = users.sum { |u| u.tasks.done.sum(:duration, :conditions => ["updated_on > ?", time]) }
# Get group_order.price for every finished order in this period
orders_sum = group_orders.includes(:order).merge(Order.finished).where('orders.ends >= ?', time).sum(:price)
update_attribute(:stats, {:jobs_size => jobs, :orders_sum => orders_sum})
end