问题
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?
回答1:
First put make a wrapper div for show.html.erb
<div class='post-<%=@post.id%>' >
<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-<%=@post.id%>").html('<%=escape_javascript @post.votes.count %>');
or something like this
来源:https://stackoverflow.com/questions/9148788/how-can-i-update-this-vote-counter-dynamically-with-ajax-javascript-rails