All threads / How do I implement voting in Rails?

Ask A Question


You’re not receiving notifications from this thread.

How do I implement voting in Rails?

karl asked in General

I have an app that has a resource called 'pins'. I want to add upvoting, and possibly downvoting, to the pins, so that I can rank them on the site Sort of like Reddit karma. I was thinking that an association called votes should be created that belongs_to a pin (which also has_many votes). How do you think I should go about this? Also, how can I differentiate in the voting object that whether it's an upvote or downvote?

Another thing, on the client side, when a user clicks upvote, how do I increment the current vote count showing on the site without reloading the page? How do I do this with JavaScript? When I tried to do this, it increases the number for all pins showing on the site, when I had clicked upvote for only one pin. Maybe this had to do with me using a single class for all the pins. What's a really good solution to this, so that the process looks seamless on the user side (number simply increments when clicked). Thanks!

Hey Karl!

This is a great question. Voting requires you to determine who did it (the voter, probably a User), what they voted on (the votable object), and which way they voted (up or down) which you could call like "direction" or you could simply store "1" or "-1" as an integer for easy calculating. 1 would represent an upvote and -1 would represent the downvote. You can basically create a model called Vote that keeps track of that information. There's a little more complexity to it when you need to sum up a user's karma based upon all the votes on their submissions, but that can be done by adding up all the votes on their submissions.

If you don't want to build all this from scratch, there's a great little gem called acts_as_votable that you can use:

It will help you create all the models and methods for voting and you basically just have to create links to actions to up and downvote submissions.

I did an episode on "liking posts" that works very similar to this. It's how I did the hearts on the GoRails episodes.

It covers most of what you want, but they're basically all considered upvotes. You'd have to add the 1 or -1 code in there to handle downvoting and keep track of which. Then your submission's karma is just the sum of all the upvotes and all the downvotes.

Hope that helps you get started!

Thank you so much! Perfect answer. Figured it out.

Join the discussion

Want to stay up-to-date with Ruby on Rails?

Join 37,344+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.

    logo Created with Sketch.

    Ruby on Rails tutorials, guides, and screencasts for web developers learning Ruby, Rails, Javascript, Turbolinks, Stimulus.js, Vue.js, and more. Icons by Icons8

    © 2020 GoRails, LLC. All rights reserved.