In many applications, we need to provide the ability to like/dislike, upvote/downvote kind of functionalities and in order to implement this, there is an awesome gem available in Ruby on Rails called “Acts as Votable” gem. These are the simple steps to follow:
Step 1: Create a sample App using the scaffold.
Step 2: Add the “acts_as_votable” gem to the Gemfile and install it by running the bundle install command.
Step 3: This Gem uses a voting table to save all voting information. To generate vote migration/ table, run the below commands:
rails g acts_as_votable:migration
Step 4: For example, I have a model called Movie, so I have added acts_as_votabe helper to it. But you can add the following to whatever model in your application which you want to make votable. In-app/models/movie.rb, I have :
Also, I need another model called User, who is going to vote. So in the app/models/user.rb, I have:
Step 5: For setting up the views to interact with the new functionality of voting I’ll need to add some routes. In app/config/routes.rb, I’ll need to add another block to my movies section.
Step 6: This block invokes the upvote and downvote methods in the movies controller, but those methods don't exist yet. So I’ll define those methods in the app/controllers/movies_controller.rb
Step 7: Finally I will create links in our views to like and dislike i.e. to implement the voting functionality in the browser.
This will create some basic links as like and dislike that, when clicked on, will update with the number of respective upvotes or downvotes for each movie.