You’re not receiving notifications from this thread.
How do I implement voting in Rails?
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?
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: https://github.com/ryanto/acts_as_votable
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. https://gorails.com/episodes/liking-posts
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!