【问题标题】:Rails, implementing voting system that only allows 1 upvote/downvote per userRails,实施投票系统,每个用户只允许 1 次 upvote/downvote
【发布时间】:2013-04-07 19:06:12
【问题描述】:

谁能告诉我为什么这段代码不起作用?在我用于测试的本地服务器上,它一直在闪烁“你已经对此进行了投票”,而我还没有。

这是我的投票控制器代码。

  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方法的正确方式吗?

【问题讨论】:

    标签: ruby-on-rails methods where vote


    【解决方案1】:

    你应该使用exists?

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

    如果您只使用current_user.votes.where(...),您将获得一个Relation 对象,该对象将始终被解释为if 中的true 值,即使Relation 不匹配任何行(仅@987654329 @ 和 nil 在 Ruby 中被视为虚假值。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-04
      • 1970-01-01
      • 2013-11-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多