如何使用 Ajax/JavaScript (Rails) 动态更新此投票计数器? [英] How can I update this vote counter dynamically with Ajax/JavaScript (Rails)?
问题描述
我构建了一个简单的投票系统:
votes_controller.rb:
class VotesController <应用控制器定义投票@post = Post.find(params[:id])@vote = @post.votes.create(:user_id => current_user.id, :polarity => 1)结尾结尾
(如果这里有任何不好的做法,请告诉我)
views/show.html.erb:
<%= @post.votes.count %>投票</h3><br/><%= link_to "Vote Up", vote_up_path(@post), :remote =>真%>
(当然我会把它放在部分中)
routes.rb:
get 'votes/:id/vote_up' =>'votes#vote_up',如:'vote_up'
当我点击投票"链接时,投票会添加到帖子中,但我必须刷新页面才能看到更改.如何使用 Ajax/JavaScript 动态刷新 @post.votes.count
和 vote.user.username
?
先为 show.html.erb 做一个包装 div
在vote_up.js.erb
$("post-<%=@post.id%>").html('<%=escape_javascript @post.votes.count %>');
或者类似的东西
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?
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
这篇关于如何使用 Ajax/JavaScript (Rails) 动态更新此投票计数器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!