title: Rails Optimize query and loop through large entity
body: <p>I have a method that outputs the following hash format for charting. </p>
  
  <pre><code># Monthly (Jan - Dec)
  {
    "john": [1,2,3,4,5,6,7,8,9,10,11,12],
    "mike": [1,2,3,4,5,6,7,8,9,10,11,12],
    "rick": [1,2,3,4,5,6,7,8,9,10,11,12]
  }
  # the indices represents the month
  # e.g [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
  # Index
  # 0 = Jan
  # 1 = Feb
  # 2 = Mar
  ...
  </code></pre>
  
  <hr>
  
  <p>The following method loops through all the store invoices within given year with specific sales rep name and generate above outcome</p>
  
  <pre><code>def chart_data
    hash = Hash.new {|h,k| h[k] = [] }
  
    (1..12).each do |month|
      date_range = "1/#{month}/#{date.year}".to_date.all_month
      all_reps.each do |name|
        hash[name] &lt;&lt; store.bw_invoices.where(sales_rep_name: name, 
        purchase_date: date_range).sum(:subtotal).to_f
      end
    end
    return hash
  end
  </code></pre>
  
  <hr>
  
  <p>When I run run this method it takes over 4~5 sec to execute. I really need to optimize this query. I came up with two solutions that I think it would help but I would love to get some of your expertise.</p>
  
  <ol>
  <li>move it to background job</li>
  <li>perform a SQL query to optimize(I need help with this if this is optimal)</li>
  </ol>
  
  <p>Thank you so much for your time </p>