2013-04-07 24 views
2

有人可以告诉我为什么这段代码不起作用吗?在我的本地服务器上进行测试,当我没有时,它会一直闪烁“你已经提高了这个”。Rails,实现投票系统,只允许每个用户1 upvote/downvote

这是在我的代表投票控制器。

def upvote 
    @vote = Vote.find(params[:post_id]) 

    if current_user.votes.where(post_id: params[:post_id], value: 1) 
     flash[:notice] = "You have already upvoted this!" 
     redirect_to :back 
    else 
     @vote.update_attributes(value: 1) 
     @vote.user_id = current_user.id 
    end 
    end 

是第4行if current_user.votes.where(post_id: params[:post_id], value: 1)正确的方法来执行where方法?

回答

4

您应该使用exists?

if current_user.votes.where(post_id: params[:post_id], value: 1).exists? 

如果你只使用current_user.votes.where(...),你将永远在if被解释为true价值Relation对象,即使tyhe Relation不匹配的任何行(只在Ruby中,falsenil被认为是falsy值)。

+0

+1,这是要走的路 – OneChillDude 2013-04-07 19:16:16