I am currently working with the Acts_As_Votable gem in Ruby to use a Like link on each of my posts so that users can vote. I found a great answer on here that helped be do exactly that but I'm trying to figure out how I can use a heart icon image instead of the Like/Dislike text. I want the image to update without refreshing, just like the text links do but can't figure out the logic. Here is the current code I am using:
controllers/prides_controller.rb
def like
@pride = Pride.find(params[:id])
@pride.liked_by current_user
if request.xhr?
render json: { count: @pride.get_likes.size, id: params[:id] }
else
redirect_to @pride
end
end
def dislike
@pride = Pride.find(params[:id])
@pride.disliked_by current_user
if request.xhr?
render json: { count: @pride.get_likes.size, id: params[:id] }
else
redirect_to @pride
end
end
prides/show.html.erb
<div class="single-heart-this">
<% if current_user.liked? @pride %>
<span class="heart-icon-loved">
<%= link_to "Dislike", dislike_pride_path(@pride), class: 'vote', method: :put, remote: true, data: { toggle_text: 'Like', toggle_href: like_pride_path(@pride), id: @pride.id } %></span>
<% else %>
<span class="heart-icon">
<%= link_to "Like", like_pride_path(@pride), class: 'vote', method: :put, remote: true, data: { toggle_text: 'Dislike', toggle_href: dislike_pride_path(@pride), id: @pride.id } %></span>
<% end %>
<span class="heart-no" data-id="<%= @pride.id %>"><%= @pride.get_likes.size %></span>
<% end %>
</div>
javascript/pride.js.erb
# 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
$(".heart-no[data-id=#{data.id}]").text data.count
return
javascript/prides.js.coffee
# Place all the behaviors and hooks related to the matching controller here.
# All this logic will automatically be available in application.js.
# You can use CoffeeScript in this file: http://coffeescript.org/
$(document).on 'ajax:success', 'a.vote', (status,data,xhr)->
# update counter
$(".heart-no[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
Thanks for your help.