The terminal says that the view was rendered but it doesn't actually renders in the browser?

Refresh

March 2019

Views

0 time

1

The following controller does the following:

If the current user's ID exists in the user_id attribute of one of the vote instances, the current user will be redirected to this page with a notice telling him that he or he already voted. If not, the vote will be cast and render views/votes/vote_up.js.erb.

votes_controller.erb:

class VotesController < ApplicationController
  def vote_up
    @post = Post.find(params[:id])

    if @post.votes.exists?(:user_id => current_user.id)
      redirect_to @post, notice: 'You already voted'
    else
      @vote = @post.votes.create(:user_id => current_user.id, :polarity => 1)
      respond_to do |format|
        format.js
      end
    end
  end
end

views/posts/show.html.erb:

<div class="post-<%[email protected]%>">
  <h3><span class="vote-count"><%= @post.votes.count %></span>votes</h3><br />
  <%= link_to "Vote Up", vote_up_path(@post), :remote => true, :class => "vote-up" %><br />
</div>

Everything works Ok except that the user is not being redirected and the notice is not appearing. I just get this notice in the terminal:

CACHE (0.0ms) SELECT "users".* FROM "users" WHERE "users"."id" = 2 ORDER BY users.created_at ASC LIMIT 1 Rendered posts/show.html.erb within layouts/application (386.5ms) Completed 200 OK in 428ms (Views: 416.5ms | ActiveRecord: 7.3ms)

Any suggestions to fix this? (by the way, is it more redable to use unless here (how)?

1 answers

2

Redirect doesn't work because you are calling the vote_up method via Ajax. You should display the notice with javascript, just like you are doing when the user hasn't voted yet.

You could do something like this:

def vote_up
  @post = Post.find(params[:id])

  if @post.votes.exists?(:user_id => current_user.id)
    @notice = 'You already voted'
  else
    @vote = @post.votes.create(:user_id => current_user.id, :polarity => 1)
  end

  respond_to do |format|
    format.js
  end
end

Then in your .erb.js file, you send back javascript depending on whether @notice and @vote are blank or not.

<% unless @notice.blank? %>
  // javascript to display @notice
<% end %>

<% unless @vote.blank? %>
  // javascript to increase vote count
<% end %>