Search code examples
ruby-on-railsif-statementacts-as-votable

Why isn't my if else statement working in controller [Rails 4]


I'm trying to make the user be able to remove his upvote by re-clicking on the upvote button

Here's my controller

  def upvote
      if current_user.voted_up_on? @post
        @post = Post.find(params[:id])
        @currentUserLikes = PublicActivity::Activity.where(trackable_id: @post.id, owner_id: current_user.id, key: "post.like")
        @currentUserLikes.destroy_all
      else  
        @post = Post.find(params[:id])
        @post.upvote_by current_user
        @post.create_activity  :like, 
                             owner: current_user,
                             recipient: @post.user
      end
  end

  def downvote
  @post = Post.find(params[:id])
  @post.downvote_by current_user
  @post.create_activity  :dislike, 
                           owner: current_user,
                           recipient: @post.user
  end

I tried placing the if else in the index but it became too complicated, why isn't it working? Note that currentUserLike is to destroy user's upvote action. and The upvote button is no more working, I didn't post the index because I didn't change it back when I didn't change the controller


Solution

  • Try this:

    def upvote
              @post = Post.find(params[:id])
              if current_user.voted_up_on? @post
                @currentUserLikes = PublicActivity::Activity.where(trackable_id: @post.id, owner_id: current_user.id, key: "post.like")
                @currentUserLikes.destroy_all
              else  
                @post.upvote_by current_user
                @post.create_activity  :like, 
                                     owner: current_user,
                                     recipient: @post.user
              end
          end