I’m having difficulty conceptualizing how to do this in the best way possible without having an enormous if/else structure. I know i could do it that way but I’m trying to abstract it into methods and I’m lost.
upvote = 1
no vote = 0
downvote = -1
Basically, a person can hit an upvote or a downvote button.
If they click upvote and their current vote is upvote, it ‘unvotes’ the post and sets it to zero
if they click downvote and their current vote is upvote, it switches it to downvote
if their vote is zero, and they click upvote, it sets the vote to 1
The inverse is true for downvote
This is what i have so far but it doesnt account for clicking upvote after you already clicked upvote.. instead of setting it to 0 it sets it to -1.
I get the problem, im just having difficulty figuring out how to write it
def update_vote(upvote_or_downvote)
self.active_vote? ? self.value = 0 : self.alternate_vote
end
def active_vote?
self.value != 0
end
def alternate_vote
self.value *= -1
end
There’s lots of ways to do it. Here’s one. I presume up_or_down will be passed as +1 for upvote and -1 for downvote. Don’t overcomplicate things.
It’s simple if you think of the logic this way:
If user clicks same thing, reset to zero. Otherwise set it to the value clicked.