Reputation: 55283
I built a simple voting system:
votes_controller.rb:
class VotesController < ApplicationController
def vote_up
@post = Post.find(params[:id])
@vote = @post.votes.create(:user_id => current_user.id, :polarity => 1)
end
end
(If there is any bad practice here, please let me know)
views/show.html.erb:
<h3><%= @post.votes.count %> votes</h3><br />
<%= link_to "Vote Up", vote_up_path(@post), :remote => true %>
(I will put this in a partial of course)
routes.rb:
get 'votes/:id/vote_up' => 'votes#vote_up', as: 'vote_up'
When I click the "Vote Up" link the vote is added to the post but I have to refresh the page in order to see the changes. How can I refresh @post.votes.count
and vote.user.username
dynamically with Ajax/JavaScript?
Upvotes: 4
Views: 2232
Reputation: 660
First put make a wrapper div for show.html.erb
<div class='post-<%[email protected]%>' >
<h3><%= @post.votes.count %> votes</h3><br />
<%= link_to "Vote Up", vote_up_path(@post), :remote => true %>
</div>
and in vote_up.js.erb
$("post-<%[email protected]%>").html('<%=escape_javascript @post.votes.count %>');
or something like this
Upvotes: 5