有人可以告诉我为什么这段代码不起作用吗?在我用于测试的本地服务器上,它一直闪烁“您已经对此表示赞成”,而我还没有这样做。
这是我的投票 Controller 代码。
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
第四行 if current_user.votes.where(post_id: params[:post_id], value: 1)
是实现 where 方法的正确方法吗?
最佳答案
您应该使用 exists?
if current_user.votes.where(post_id: params[:post_id], value: 1).exists?
如果您仅使用current_user.votes.where(...)
,您会得到 Relation
始终被解释为 true
的对象if
中的值,即使您Relation
不匹配任何行(Ruby 中只有 false
和 nil
被视为假值)。
关于ruby-on-rails - Rails,实现投票系统,每个用户只允许 1 个赞成票/反对票,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15866572/