13

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?

Aldwoni
  • 1,168
  • 10
  • 24
gd_silva
  • 997
  • 2
  • 11
  • 17

1 Answers1

31

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
    
gd_silva
  • 997
  • 2
  • 11
  • 17
DMKE
  • 4,553
  • 1
  • 31
  • 50
  • Hi. Thanks for the answer. I've done exactly what you said above (put the JS in the scaffold created `contents.js.coffee`) but when I click the link, the number doesn't update in real time. It just updates after a refresh... – gd_silva Jun 14 '14 at 16:23
  • Did you `//= require content` in your `application.js` (or `//= require_tree .` for that matter)? – DMKE Jun 14 '14 at 16:40
  • Yes, I did `//= require_tree .` – gd_silva Jun 14 '14 at 16:48
  • My bad, the event callback has the parameters `status` and `data` swapped, I'll update the answer. – DMKE Jun 14 '14 at 17:09
  • How could I change the text in the button (and the action) along with the count number? – gd_silva Jun 14 '14 at 17:33
  • What I want to do is to change from "Like" to "Dislike", updating also the controller action that is called. How do I do that? – gd_silva Jun 14 '14 at 18:35
  • That's questioned in my question, so if I create a new post it will be repost. Could you edit your answer to help me? – gd_silva Jun 14 '14 at 21:49
  • Found the error. You're calling `toggle-text` instead of `toggle_text`. Same for `toggle-href`. Also, there's a `)` missing at the end. – gd_silva Jun 16 '14 at 13:07
  • At the end, what I said is not correct. Something is missing for it to work. Update your answer and I'll accept it. – gd_silva Jun 16 '14 at 13:12
  • 1
    Found the main problem: `remote: true` was missing in the `link_to` helper. Of course, the CoffeeScript error had to be fixed, too (see [revisions](http://stackoverflow.com/posts/24221646/revisions) for details). – DMKE Jun 16 '14 at 17:51
  • I would use a POST instead of PUT. – vasilakisfil Apr 28 '15 at 11:20