Acts as a voice javascript vote button

I use a gem called acts_as_votable to make my model voting.

Everything is working now.

But every time someone votes for a message, the page should be updated. How to make voting work without refreshing the page. Is there any simple javascript I can add?

Here is what I have in the controller:

def vote @post = Post.find(params[:post_id]) @post.liked_by current_user respond_to do |format| format.html {redirect_to :back } end end 

Here is what I mean:

  <%= link_to "like post", like_post_path(@post), method: :put %> 
+7
javascript ruby ruby-on-rails ruby-on-rails-4
source share
3 answers

A very simple version might look like this:

Ruby

 def vote @post = Post.find(params[:post_id]) @post.liked_by current_user respond_to do |format| format.html {redirect_to :back } format.json { render json: { count: @post.liked_count } } end end 

HTML

 <%= link_to 'like', vote_path(@post), class: 'vote', remote: true, data: { type: :json } %> 

Js

 $('.vote') .on('ajax:send', function () { $(this).addClass('loading'); }) .on('ajax:complete', function () { $(this).removeClass('loading'); }) .on('ajax:error', function () { $(this).after('<div class="error">There was an issue.</div>'); }) .on('ajax:success', function (data) { $(this).html(data.count); }); 

This is a very rudimentary version that shows a basic approach, but has some obvious pitfalls:

  • Unable to "display"
  • The download indicator is small UX; with JS, we can always display the current state of the user and deal with synchronization with the server in the background.
  • Any caching of HTML in the view will blow it.
+9
source share

Simple Remove your answer block:

 def vote @post = Post.find(params[:post_id]) @post.liked_by current_user end 

and press the button of the remote control:

 <%= link_to "like post", like_post_path(@post), method: :put, remote: true %> 

If you want to run a script when a person votes for a message or something else, create a vote.js.erb file (under the rails naming convention) and place it in the view folder. You can put javascript in it, which will be launched when accessing the controller action.

PS, are you sure the like_post_path points to your vote controller?

+5
source share

Ruby on Rails provides Ajax helpers for this. For example:

 <%= link_to "like post", like_post_path(@post), method: :put, remote: true %> 

But then you will need to manually update the vote counter using JavaScript.

+2
source share

All Articles