Search code examples
javascriptruby-on-railsrubyajaxsocial-media-like

Like button Ajax in Ruby on Rails


I have a Ruby on Rails project with a model User and a model Content, among others. I wanted to make possible for a user to "like" a content, and I've done that with the acts_as_votable gem.

At the moment, the liking system is working but I'm refreshing the page every time the like button (link_to) is pressed.

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.

In my Content -> Show view, this is what I have:

<% if user_signed_in? %>
  <% if current_user.liked? @content %>
      <%= link_to "Dislike", dislike_content_path(@content), class: 'vote', method: :put %>
  <% else %>
      <%= link_to "Like", like_content_path(@content), class: 'vote', method: :put %>
  <% end %>
  <span> · </span>
<% end %>

<%= @content.get_likes.size %> users like this
<br>

The Content controller does this to like/dislike:

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

And in my routes.rb file, this is what I have:

resources :contents do
    member do
        put "like", to: "contents#like"
        put "dislike", to: "contents#dislike"
    end
end

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 redirect_to @content in the controller action.

How could I implement this with a simple Ajax call? Is there another way to do it?


Solution

  • You can do so in various ways, the simple way goes like this:

    Preparations

    1. Include Rails UJS and jQuery in your application.js (if not already done so):

      //= require jquery
      //= require jquery_ujs
      
    2. Add remote: true to your link_to helpers:

      <%= link_to "Like", '...', class: 'vote', method: :put, remote: true %>
      
    3. Let the controller answer with a non-redirect on AJAX requests:

      def like
        @content = Content.find(params[:id])
        @content.liked_by current_user
      
        if request.xhr?
          head :ok
        else
          redirect_to @content
        end
      end
      

    Advanced behaviour

    You probably want to update the "n users liked this" display. To archieve that, follow these steps:

    1. Add a handle to your counter value, so you can find it later with JS:

      <span class="votes-count" data-id="<%= @content.id %>">
        <%= @content.get_likes.size %>
      </span>
      users like this
      

      Please also note the use of data-id, not id. If this snippet gets used often, I'd refactor it into a helper method.

    2. Let the controller answer with the count and not simply an "OK" (plus add some information to find the counter on the page; the keys are arbitrary):

      #…
      if request.xhr?
        render json: { count: @content.get_likes.size, id: params[:id] }
      else
      #…
      
    3. Build a JS (I'd prefer CoffeeScript) to react on the AJAX request:

      # Rails creates this event, when the link_to(remote: true)
      # successfully executes
      $(document).on 'ajax:success', 'a.vote', (status,data,xhr)->
        # the `data` parameter is the decoded JSON object
        $(".votes-count[data-id=#{data.id}]").text data.count
        return
      

      Again, we're using the data-id attribute, to update only the affected counters.

    Toggle between states

    To dynamically change the link from "like" to "dislike" and vice versa, you need these modifications:

    1. Modify your view:

      <% if current_user.liked? @content %>
        <%= link_to "Dislike", dislike_content_path(@content), class: 'vote', method: :put, remote: true, data: { toggle_text: 'Like', toggle_href: like_content_path(@content), id: @content.id } %>
      <% else %>
        <%= link_to "Like", like_content_path(@content), class: 'vote', method: :put, remote: true, data: { toggle_text: 'Dislike', toggle_href: dislike_content_path(@content), id: @content.id } %>
      <% end %>
      

      Again: This should go into a helper method (e.g. vote_link current_user, @content).

    2. And your CoffeeScript:

      $(document).on 'ajax:success', 'a.vote', (status,data,xhr)->
        # update counter
        $(".votes-count[data-id=#{data.id}]").text data.count
      
        # toggle links
        $("a.vote[data-id=#{data.id}]").each ->
          $a = $(this)
          href = $a.attr 'href'
          text = $a.text()
          $a.text($a.data('toggle-text')).attr 'href', $a.data('toggle-href')
          $a.data('toggle-text', text).data 'toggle-href', href
          return
      
        return