ruby-on-rails - Rails,实现投票系统,每个用户只允许 1 个赞成票/反对票

标签 ruby-on-rails methods where-clause vote

有人可以告诉我为什么这段代码不起作用吗?在我用于测试的本地服务器上,它一直闪烁“您已经对此表示赞成”,而我还没有这样做。

这是我的投票 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 中只有 falsenil 被视为假值)。

关于ruby-on-rails - Rails,实现投票系统,每个用户只允许 1 个赞成票/反对票,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15866572/

相关文章:

python - 从 numpy 数组中查找并删除列

ruby-on-rails - Puma 输出像薄带 rails

ruby-on-rails - 我有一个具有以下 namespace 的 ruby​​ View :ActionView::Base.new 但我想添加一个新方法可用于此 ActionView::Base 类

ruby-on-rails - 分离的 gem 上的rake gems:refresh_specs错误

ios - 方法参数@selector

mysql - 如何使用 WHERE 子句和 INNER JOIN 从列中获取所有行

sql - 如何根据位于另一个表中的具有特定属性的列选择 SQLite 表的项目?

ruby-on-rails - 如何在生产模式下修复 Rails 的布线错误?

c++ - 成员函数与传递对全局函数的引用相同吗?

c# - 将方法指针从 C# 传递到 Delphi DLL