我正在尝试使用thumbs_up gem显示在帖子上投票的总票数,但它似乎不起作用。
这是我的代码
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
在视图中: -
<%="Total votes = #{@votes_total}"%>
我收到了“您已成功投票”的消息,但我的投票数量未显示。
这就是我在日志文件中的内容: -
[1m [36m(0.3ms)[0m [1mSELECT COUNT(*)FROM“投票”在哪里 “vote”。“voteable_id”= 12 AND“votes”。“voteable_type”=“发布”AND “投票”。“投票”='t'[0m 0
---更新---
使用以下代码更新我的帖子控制器: -
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
请帮助。
答案 0 :(得分:1)
因为您正在重定向而无法显示。重定向时,您基本上是在执行新请求,而前一个请求的实例变量将不再可用。 Flash确实有效,因为它使用session
。解决方案:在您要重定向到的操作中设置@votes_total
,或使用render
代替redirect_to
。
答案 1 :(得分:0)
尝试更改
@votes_total
到
@ post.votes_for或相应的等效
在视图中。