Skip to content

Upvote and downvote a Scenario

John Knapp edited this page Mar 6, 2018 · 6 revisions

Steps

install the Gem

gem install acts_as_votable

Do the migration using the votable migration helper

rails generate acts_as_votable:migration
rake db:migrate

find the model to which up voting and down voting to be applied

if we have the model Post model

class Post < ApplicationRecord
 acts_as_votable
end

Update the routes

now we need to update the routes

resources :posts do
 member do
  put "like", to: "posts#upvote"
  put "dislike", to: "posts#downvote"
 end
end

create 2 custom methods

def upvote
 @post.upvote_by current_user
 redirect_to @post
end

def downvote
 @post.downvote_by current_user
 redirect_to @post
end

Note: You probably want to add these two methods to your before_action callback. If you're using CanCanCan, you may want to add these upvote and downvote methods there too.

Now we need to update the views

<%=link_to like_post_path(@post), method: :put, class: 'btn btn-default btn-sm' do %>
 <span class="glyphicon glyphicon-chevron-up"></span>
 like <%=@post.get_upvotes.size%></td>
<% end %>
<%=link_to dislike_post_path(@post), method: :put, class: 'btn btn-default btn-sm' do %>
 <span class="glyphicon glyphicon-chevron-down"></span>
 dislike <%=@post.get_downvotes.size%></td>
<%end%>