Here is my solution. Project: the user can create a message (debat), and other users can raise and lower the level using the buttons.
What else:
ajax updates downvoteS counting and upvotes counting simultaneously when user clicks. I used .text instead of .html in my javascript files. I did not use partial, I put all my code in debat.html.erb. I created a special class for each button with a range and a variable identifier, because all the buttons changed at the same time
My .rb routes are the same:
resources :debats do member do put "like", to: "debats#upvote" put "dislike", to: "debats#downvote" end end
dabats_controller.rb:
def upvote @debat = Debat.find(params[:id]) @debat.upvote_by current_user respond_to do |format| format.html {redirect_to :back } format.json { render json: { count: @debat.liked_count } } format.js { render :layout => false } end end def downvote @debat = Debat.find(params[:id]) @debat.downvote_by current_user respond_to do |format| format.html {redirect_to :back } format.json { render json: { count: @debat.disliked_count } } format.js { render :layout => false } end end
debat.html.erb (only two-button part)
<div class="large-1 columns count"> <span class= "like-<%= debat.id %>"> <%= link_to like_debat_path(debat), method: :put, remote: true, class: 'like' do %> <div class="upcount"><i class="fa fa-angle-up"></i></div> <div class="ouicount up-<%= debat.id %>"><%= debat.get_upvotes.size %></div> <div class="oui">Oui</div> <%end%> </span> <span class= "dislike-<%= debat.id %>"> <%= link_to dislike_debat_path(debat), method: :put, remote: true, class: 'dislike' do %> <div class="non">Non</div> <div class="noncount down-<%= debat.id%>"> <%= debat.get_downvotes.size %></div> <div class="downcount"><i class="fa fa-angle-down"></i></div> <% end %> </span> </div>
upvote.js.erb
$('.like').bind('ajax:success', function() { $('.up-<%= @debat.id %>').text(<%= @debat.get_upvotes.size%>); $('.down-<%= @debat.id %>').text(<%= @debat.get_downvotes.size%>); });
downvote.js.erb
$('.dislike').bind('ajax:success', function() { $('.up-<%= @debat.id %>').text(<%= @debat.get_upvotes.size%>); $('.down-<%= @debat.id %>').text(<%= @debat.get_downvotes.size%>); });
Hope this helps!
source share