How can I update the vote counter dynamically using Ajax / JavaScript (Rails)?

I created 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 you have bad practice, let me know)

view /show.html.erb:

 <h3><%= @post.votes.count %> votes</h3><br /> <%= link_to "Vote Up", vote_up_path(@post), :remote => true %> 

(I'll put it in partial, of course)

routes.rb:

 get 'votes/:id/vote_up' => 'votes#vote_up', as: 'vote_up' 

When I click on the Vote link, a vote is added to the message, but I have to refresh the page to see the changes. How to update @post.votes.count and vote.user.username dynamically using Ajax / JavaScript?

+4
source share
1 answer

First put make 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 that

+5
source

Source: https://habr.com/ru/post/1394846/


All Articles