Displaying total votes count with thumbs_up

686 Views Asked by At

I am trying to display total votes cast on a post with thumbs_up gem but it does not seem to work.

Here is my code

    def vote_up
    begin
      post = Post.find(params[:id])
      current_user.vote_for(post)
      redirect_to :back
      flash[:sucess] = "You have voted successfully"
      @votes_total = post.votes_for
    rescue ActiveRecord::RecordInvalid
        redirect_to :back
        flash[:error] = "You have already voted for this one"
    end

  end

In the view :-

<%="Total votes = #{@votes_total}"%>

I get the flash message "You have voted successfully" but my votes count are not getting displayed.

This is what I have in my log files :-

[1m[36m (0.3ms)[0m [1mSELECT COUNT(*) FROM "votes" WHERE "votes"."voteable_id" = 12 AND "votes"."voteable_type" = 'Post' AND "votes"."vote" = 't'[0m 0

--- Update ---

Update my post controller with this code :-

def vote_up
    begin
      post = Post.find(params[:id])
      current_user.vote_for(post)
      @votes_total = post.votes_for
      render :template => "home/index"
      flash[:sucess] = "You have voted successfully"

    rescue ActiveRecord::RecordInvalid
        redirect_to :back
        flash[:error] = "You have already voted for this one"
    end

  end

Help please.

2

There are 2 best solutions below

7
On BEST ANSWER

It does not display because you are redirecting. When redirecting you are basically doing a new request and the instance variables of the former request won't be available anymore. Flash does work, because it uses the session. Solution: either set @votes_total in the action you are redirecting to or use render instead of redirect_to.

1
On

try changing

@votes_total

to the

@post.votes_for or corresponding equivalent

in the view.