Ruby on Rails: strange voting increment behavior

Posted by Justin Meltzer on Stack Overflow See other posts from Stack Overflow or by Justin Meltzer
Published on 2011-03-18T07:09:19Z Indexed on 2011/03/18 8:10 UTC
Read the original article Hit count: 432

So I have an up and a downvote button that inserts a vote with a value of 1 or -1 into the database. This works correctly. Then, I display the total vote count for that element by summing up its votes' values. However, this isn't working correctly, because the vote sum display is acting really strange:

The first vote on a video doesn't seem to increment it at all. Then the second vote does. If I go from an upvote to a downvote, it increments up once, and then the next downvote is down. This is difficult to explain, but maybe you can figure out what is wrong with my code.

I have this function in my Video model (the element that is voted on, it has_many video_votes):

def vote_sum
  read_attribute(:vote_sum) || video_votes.sum(:value)
end

I also have this in my VideoVote model:

after_create :update_vote_sum

private

  def update_vote_sum
    video.update_attributes(:vote_sum => video.vote_sum + value)
  end

What am I doing wrong?

© Stack Overflow or respective owner

Related posts about ruby-on-rails

Related posts about ruby