I just successfully created a voting system and I would like to make one button do both the voting up and down instead of two buttons. I am trying to work my way around the js file for this but I still see two buttons, any suggestions? Thank you.
Micropost Controller
class MicropostsController < ApplicationController
def vote_up
@micropost = Micropost.find(params[:id])
current_user.vote_exclusively_for(@micropost)
respond_to do |format|
format.html { redirect_to :back }
format.js
end
end
def unvote
@micropost = Micropost.find(params[:id])
current_user.vote_exclusively_against(@micropost)
respond_to do |format|
format.html { redirect_to :back }
format.js
end
end
end
JS Files
*vote_up.js*
$("#<%=micropost.id%>").html('<%= "#{micropost.votes_for}" %>');
$(".<%=micropost.id%>").html('<a href="/microposts/<%= micropost.id%>/unvote" data-remote="true" class="SquekCounterButton b2 <%= micropost.id%>"><span class="SquekCounterIcon <%= micropost.id%>"></span></a>');
unvote.js
$("#<%=micropost.id%>").html('<%= "#{micropost.votes_for}" %>');
$(".<%=micropost.id%>").html('<a href="/microposts/<%= micropost.id%>/vote_up" data-remote="true" class="CounterButton b2 <%= micropost.id%>"><span class="CounterIcon <%= micropost.id%>"></span></a>');
Micropost HTML
<div class='Counter'>
<span class='CounterNum'><span id='<%= micropost.id%>'><%=micropost.votes_for %></span></span>
<div class='<%=micropost.id %>'>
<a href="/microposts/<%=micropost.id %>/vote_up" data-remote='true' class='CounterButton b2'>
<span class='CounterIcon'></span>
</a>
</div>
<div class='<%=micropost.id %>'>
<a href="/microposts/<%=micropost.id %>/unvote" data-remote='true'class='CounterButton b2'>
<span class='CounterIcon'></span>
</a>
</div>
</div>
A different approach:
Create only one action, “toggle_vote” instead “vote_up”, “vote_down”. First call to “toggle_vote” will “vote_up”, second call “vote_down”, etc..
“vote_toggle.js.erb” should update button status depending on vote status.