Building a Reddit Clone Pt.4

We want our users to vote up or down on someone else’s link. To do so, we use the power of a gem called acts as votable.

( i found out that some gems like devise, which we used before, need a server restart to work properly as does acts as votable)

Added the gem to our gemfile and restarted the local server, we need to run:

rails g acts_as_votable:migration

to add voting abilities to our table data base.

also, adding acts_as_votable in the link.rb model is necessary.

To add the voting system to our views we have to set routes for it in routes.rb:

Rails.application.routes.draw do
devise_for :users
 resources :links do
      member do
             put ‘like’, to: “links#upvote”
             put ‘dislike’, to: “links#downvote”


root to: ‘links#index’

after that we need to define a upvote and downvote method in our links_controller.rb file with:

def upvote
@link = Link.find(params[:id])
@link.upvote_by current_user
redirect_to :back

def downvote
@link = Link.find(params[:id])
@link.downvote_by current_user
redirect_to :back

translating the code to english: define a variable called @link, to find the link that we want to down/upvote in the database by ID. Then assign it to the current user. Finally send the user “back” a page.

Adding down/upvote buttons is the last thing left to do.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s