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-<%=@post.id%>">
<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)?
Redirect doesn’t work because you are calling the
vote_upmethod 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:
Then in your
.erb.jsfile, you send back javascript depending on whether@noticeand@voteare blank or not.