title: Calculating karma from upvotes/downvotes on a user's posts
body: <p>I have a User and Post model and am using the <a href="https://github.com/ryanto/acts_as_votable" rel="nofollow">acts_as_votable</a> gem (which gives me a 'votes' table) to upvote/downvote a post. I want to assign karma to each user, where karma is the number of upvotes a user has gained from all his/her posts minus the total number of downvotes.</p>
  
  <p>Currently I have this instance method on the User's model to calculate karma:</p>
  
  <pre><code>  def karma
      count = 0
      self.posts.each do |post|
        count += post.upvotes.size - post.downvotes.size
      end
      return count
    end
  </code></pre>
  
  <p>I don't think the above is very efficient with a run time of O(2n), because for every post two additional database queries are required, one for the upvotes, and one for the downvotes.</p>
  
  <p>Any ideas on how to combined the above into a single query, or otherwise make it more efficient?</p>