ruby on rails - Calculating karma from upvotes/downvotes on a user's posts -
i have user , post model , using acts_as_votable gem (which gives me 'votes' table) upvote/downvote post. want assign karma each user, karma number of upvotes user has gained his/her posts minus total number of downvotes.
currently have instance method on user's model calculate karma:
def karma count = 0 self.posts.each |post| count += post.upvotes.size - post.downvotes.size end return count end
i don't think above efficient run time of o(2n), because every post 2 additional database queries required, 1 upvotes, , 1 downvotes.
any ideas on how combined above single query, or otherwise make more efficient?
not efficiency, such design not in terms of oop. user model considers beyond scope. karma belongs user , should not tied in else.
a better approach separate "karma" post.
# add "karma" column $ rails g migration addkarmatouser # or use dedicated table class user < activerecord::base has_one :karma
then, use controller or service object change karma. i'll cover controller here simplicity. not use model callbacks cross models.
class postscontroller < applicationcontroller def upvote post = post.find(params[:id]) post.upvote # pseudo api of acts_as_votable current_user.increase_karma end def downvote # ... current_user.decrease_karma end end # model class user < activerecord::base attr_accessible :karma def increase_karma(count=1) update_attribute(:karma, karma + count) end def descrease_karma(count=1) # ... end end # view user.karma
Comments
Post a Comment