title: Like button Ajax in Ruby on Rails
body: <p>I have a Ruby on Rails project with a model <code>User</code> and a model <code>Content</code>, among others. I wanted to make possible for a user to "like" a content, and I've done that with the <a href="https://github.com/ryanto/acts_as_votable">acts_as_votable</a> gem.</p>
  
  <p>At the moment, the liking system is working but I'm refreshing the page every time the like button (link_to) is pressed.</p>
  
  <p>I'd like to do this using Ajax, in order to update the button and the likes counter without the need to refresh the page.</p>
  
  <p>In my <code>Content -&gt; Show</code> view, this is what I have:</p>
  
  <pre><code>&lt;% if user_signed_in? %&gt;
    &lt;% if current_user.liked? @content %&gt;
        &lt;%= link_to "Dislike", dislike_content_path(@content), class: 'vote', method: :put %&gt;
    &lt;% else %&gt;
        &lt;%= link_to "Like", like_content_path(@content), class: 'vote', method: :put %&gt;
    &lt;% end %&gt;
    &lt;span&gt; · &lt;/span&gt;
  &lt;% end %&gt;
  
  &lt;%= @content.get_likes.size %&gt; users like this
  &lt;br&gt;
  </code></pre>
  
  <p>The <code>Content</code> controller does this to like/dislike:</p>
  
  <pre><code>def like
      @content = Content.find(params[:id])
      @content.liked_by current_user
      redirect_to @content
  end
  
  def dislike
      @content = Content.find(params[:id])
      @content.disliked_by current_user
      redirect_to @content
  end
  </code></pre>
  
  <p>And in my routes.rb file, this is what I have:</p>
  
  <pre><code>resources :contents do
      member do
          put "like", to: "contents#like"
          put "dislike", to: "contents#dislike"
      end
  end
  </code></pre>
  
  <p>As I said, the liking system is working fine, but does not update the likes counter nor the like button after a user presses it. Instead, to trick that, I call <code>redirect_to @content</code> in the controller action.</p>
  
  <p>How could I implement this with a simple Ajax call? Is there another way to do it?</p>