title: Why doesn't this Ruby on Rails voting code work?
body: <p>So I really thought this would work to create the voting system like we have here on SO:</p>
  
  <pre><code>def create       
    @video = Video.find(params[:video_id])
    @vote = current_user.video_votes.find_or_create_by_video_id(@video.id)
  
    if @vote.value.nil?
      if params[:type] == "up"
        @vote.value = 1
      else
        @vote.value = -1
      end
    elsif (params[:type] == "up" &amp;&amp; @vote.value == 1) || (params[:type] == "down" &amp;&amp; @vote.value == -1)
      @vote.value = 0
    elsif ((params[:type] == "up" &amp;&amp; @vote.value == -1) || (params[:type] == "down" &amp;&amp; @vote.value == 1)) || (@vote.value == 0)
      if params[:type] == "up"
        @vote.value = 1
      else
        @vote.value = -1
      end
    end  
  
    if @vote.save
      respond_to do |format|
        format.html { redirect_to @video }
        format.js
      end
    else
      respond_to do |format|
        format.html { redirect_to @video }
        format.js {render 'fail_create.js.erb'}
      end
    end   
  end
  </code></pre>
  
  <p>I tried to follow the example of the first answer in this question: <a href="https://stackoverflow.com/questions/5360914/why-doesnt-this-ruby-on-rails-code-work-as-i-intend-it-to">Why doesn&#39;t this Ruby on Rails code work as I intend it to?</a> My code, however, doesn't let me vote on a video for the first time because of this error:</p>
  
  <pre><code>TypeError (nil can't be coerced into Fixnum):
  app/models/video_vote.rb:11:in `update_vote_sum'
  app/controllers/video_votes_controller.rb:4:in `create
  </code></pre>
  
  <p>Here's my videovote model:</p>
  
  <pre><code>class VideoVote &lt; ActiveRecord::Base
    belongs_to :user
    belongs_to :video
    validates_uniqueness_of :user_id, :scope =&gt; :video_id
  
    after_create :update_vote_sum
  
    private
  
      def update_vote_sum
        video.update_attributes!(:vote_sum =&gt; video.vote_sum + value)
      end
  end
  </code></pre>
  
  <p>And in case this is needed, here's my <code>vote_sum</code> method from my Video model:</p>
  
  <pre><code>def vote_sum
    video_votes.sum(:value)
  end
  </code></pre>