Question

Can someone tell me why this code doesn't work? On my local server for testing, it keeps flashing "You have already upvoted this" when I haven't.

This is in my code for the votes controller.

  def upvote
    @vote = Vote.find(params[:post_id])

    if current_user.votes.where(post_id: params[:post_id], value: 1)
      flash[:notice] =  "You have already upvoted this!"
      redirect_to :back
    else
      @vote.update_attributes(value: 1)
      @vote.user_id = current_user.id
    end
  end

Is the 4th line if current_user.votes.where(post_id: params[:post_id], value: 1) the correct way to implement the where method?

Was it helpful?

Solution

You should use exists?

if current_user.votes.where(post_id: params[:post_id], value: 1).exists?

If you use only current_user.votes.where(...), you get a Relation object that will always be interpreted as a true value in the if, even if tyhe Relation do not match any line (only false and nil are considered as falsy values in Ruby).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top