Reputation: 2443
I'm trying to do a very simple voting module with an AJAX call. Unfortunately I've been stuck with this for about 4 days now. I'm still very new to Rails and I'd love to figure out what I'm doing wrong here!
The concept of the website is pretty straightforward. There's a list of posts (called Topic) that users can vote on. I've used Devise for user models and Thumbs_up for voting.
Here's the view snippet: index.html.erb
<td id='topic_<%=topic.id%>_votes'> <%= pluralize(topic.votes.count, "vote") %> </td>
<td><%= link_to('Vote for this post!', vote_up_topic_path(topic), :method => :post, :remote => true) %></td>
Here's the controller: topics_controller.rb
def vote_up
current_user.vote_exclusively_for(@topic = Topic.find(params[:id]))
respond_to do |format|
format.js
end
end
Here's the JavaScript: vote_up.js.erb in views/topics
<% if current_user.voted_on?(@topic = Topic.find(params[:id])) %>
$('topic_<%[email protected]%>_votes').html('<%= pluralize(@topic.votes.count, "vote") %>');
<% else %>
alert("You can only vote on <%= @topic.title %> once!")
<% end %>
When I start up the Rails server and click on the vote link, I can see (in the terminal) that it does process the vote_up.js.erb file, but there's no change in the browser. Only when I refresh it, does it show the increased number of votes. The vote is being recorded in the DB but there's no acknowledgement of it in the browser.
What am I doing wrong here?
Upvotes: 2
Views: 179
Reputation: 770
Since you're using ID for that Div, add a '#' before topic_<%[email protected]%>_votes in your vote_up.js.erb code.
This is how it should be:
$('#topic_<%[email protected]%>_votes').html('<%= pluralize(@topic.votes.count, "vote") %>');
Upvotes: 2