Search⌘ K

Acts as Votable

Explore how to add voting functionality to your Rails application using the acts_as_votable gem. Understand setting up migrations, configuring voter and votable models, creating controller actions for like and unlike, modifying routes, and updating views to reflect vote counts. This lesson enables you to implement interactive voting features efficiently.

The next thing you will be adding to your application is a way to upvote/downvote links. To do this, you will be using the acts_as_votable Ruby gem.

The gem allows you to perform actions such as upvote/downvote for any of your ActiveRecord models. Any model can vote, and any model can be voted on.

Migrations

The acts_as_votable gem uses a votes table to store all the information relating to your upvotes/downvotes.

To create an acts_as_votable migration and run it, you will use the following commands:

rails g acts_as_votable:migration
rake db:migrate

The above commands will generate the votes table to keep a record of the votes


Voter and votable

Now that you have a votes table, you need to decide which of your models will be votable, and which model will be casting the votes.

Voter

In this case, you will want the User model to be the voter. Users will be casting votes on different links that are submitted.

You will add the following line to your app/models/user.rb file:

acts_as_voter

Votable

Now that the User ...