I have a User and Post model and am using the acts_as_votable 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.
Currently I have this instance method on the User's model to calculate karma:
def karma
count = 0
self.posts.each do |post|
count += post.upvotes.size - post.downvotes.size
end
return count
end
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.
Any ideas on how to combined the above into a single query, or otherwise make it more efficient?