I am using the "Acts As Votable" gem in my application because I want to allow my user to like and dislike comments. It has been working good so far, but now I want to implement Ajax to improve the user interface.
This is my code:
routes.rb:
resources :articles do
member do
put "like", to: "articles#upvote"
end
resources :comments do
member do
get "like", to: "comments#upvote"
get "dislike", to: "comments#downvote"
end
end
end
comments_controller.rb:
def upvote
if @comment.upvote_from current_user
respond_to do |format|
format.html { redirect_to(:back) }
format.js
end
end
end
def downvote
if @comment.downvote_from current_user
respond_to do |format|
format.html { redirect_to(:back) }
format.js
end
end
end
_comment.html.erb:
<span class="like-comment">
<%= link_to like_article_comment_url(@article, comment), method: :get, remote: true do %>
<span class="fa fa-thumbs-up" id="thumbs-up"> <%= comment.get_upvotes.size %></span>
<% end %>
</span>
<p class="dislike-comment">
<%= link_to dislike_article_comment_url(@article, comment), method: :get, remote: true do %>
<span class="fa fa-thumbs-down" id="thumbs-down"> <%= comment.get_downvotes.size %></span>
<% end %>
upvote.js.erb:
$('#thumbs-up').replaceWith("<%= j render comment.get_upvotes.size %>");
downvote.js.erb:
$('#thumbs-down').replaceWith("<%= j render comment.get_downvotes.size %>");
The problem is it doesn't update the number of like/dislike when I click the like/dislike button. However, when I refresh the page, it updates the number of like/dislike. I don't know why the view doesn't update the number of like/dislike. Moreover, I tried to change the file to upvote.erb.js/downvote.erb.js as other people suggested but the problem is still there.
*Updated: When I opened the network console in firefox, I saw 500 internal server error when I clicked the like/dislike butto. I searched all the problem related with that error, but still couldn't figure what is wrong with my code.