-
Notifications
You must be signed in to change notification settings - Fork 216
Slightly More Advanced Controller Method
Chris Korhonen edited this page Aug 22, 2018
·
2 revisions
This controller code will check if the user has already voted and will check if the user is voting for their own posted "movie". I used "movie" as a placeholder for what I had so the wording may be a little clunky, but this would obviously be better checks for a post since you might not want users voting for their own post. I also put in flash messages letting the user know what’s going on.
# Begin - Acts_as_votable Controller methods for movies.
# Begin - Sets up upvote method.
def upvote
# Before action that Finds movie.
# Begin - If statement to check for user voting on their own movie or not.
if @movie.user != current_user # User who is voting for the movie is not the user who created it.
# Begin - If statement for determining if user has already voted for movie or not.
if current_user.voted_for? @movie # Checks for :true if user has already voted for movie. Goes to Else if user has not yet voted for movie.
# Below - User has not yet voted for movie and user has not posted the movie they're voting for.
flash[:alert] = "You have already upvoted this movie."
redirect_to movies_path
else # User is voting on the movie for the first time since the If statement came back as :false.
# Below - User has passed both if statments to successfully vote for the movie.
@movie.upvote_by current_user
if @movie.save! # User successfully votes for movie.
flash[:notice] = "You have successfuly upvoted #{@movie.name}"
redirect_to movies_path
else # For some reason, user couldn't vote for movie.
flash[:alert] = "Could not upvote this #{@movie.name}"
redirect_to movies_path
end # End - If statement of user voting for movie.
end # End - If statement for determining if user has already voted for movie or not.
else # User who is voting for the movie is the user who created the movie.
flash[:alert] = "You cannot upvote your own movie."
redirect_to movies_path
end # End - If statement to check for user voting on their own movie or not.
end # End - Sets up upvote method.