title: Improve performance of my ActiveRecord query
body: <p>I am trying writing a query that gets all the <code>User</code> statuses, and the count of those statuses. My approach, however, is very expensive, and is taking a toll on the database by making tons of queries.</p>
  
  <p>I'm still new to this, and want to refactor this code so it will stop timing out. Below is the code I have so far:</p>
  
  <p><strong>User model:</strong></p>
  
  <pre><code># app/models/user.rb
  class User &lt; ApplicationActiveRecordBase
    has_many :purchases
  end
  </code></pre>
  
  <p><strong>Purchase model:</strong></p>
  
  <pre><code># app/models/purchase.rb
  class Purchase &lt; ApplicationActiveRecordBase
    belongs_to :user
  end
  </code></pre>
  
  <p><strong>Schema:</strong></p>
  
  <pre><code># app/db/schema.rb
  create_table "users", force: :cascade do |t|
    t.boolean  "has_registered"
    t.boolean "has_unsubscribed"
  end
  
  create_table "purchases", force: :cascade do |t|
    t.string "item"
    t.integer "price"
    t.integer "user_id"
  end
  </code></pre>
  
  <p><strong>Code that I want to optimize:</strong></p>
  
  <pre><code>status = Hash.new(0)
  User.find_each do |user|
    status[check_user_status(user)] += 1
  end
  
  def check_user_status(user)
    if user.purchases.count &gt; 0
      'purchased'
    elsif user.has_registered?
      'registered'
    elsif user.has_unsubscribed?
      'unsubscribed'
    end
  end
  </code></pre>