How can I update this vote counter dynamically with Ajax/JavaScript (Rails)?

核能气质少年 提交于 2020-01-10 19:55:29

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!