返回零的地方?

时间:2013-12-14 22:47:44

标签: ruby-on-rails ruby

  def new
    @host = Host.find(params[:id])
    @lastreview = Review.where("user_id = ? AND host_id = ?", current_user[:id], @host.id)
    if @lastreview == nil
        @review = Review.new
    else
        redirect_to @host, notice: "You already posted a review for this host!"
    end
  end

出于某种原因,即使他们没有评论,也没有返回nil?我误解了用法吗?

2 个答案:

答案 0 :(得分:0)

where返回一个数组 - 如果表中没有符合条件的评论,它返回的数组将为空,但它永远不会为零。

请改为尝试:

if @lastreview.empty?
    @review = Review.new
else
    redirect_to @host, notice: "You already posted a review for this host!"
end

答案 1 :(得分:0)

如果您实际上不需要最后的记录,可以使用exists?

  

如果表中存在与给定的id或条件匹配的记录,则返回true,否则返回false

这应该有效(如果一切设置正确,Rails可以处理_id后缀):

def new
  @host = Host.find(params[:id])
  if Review.exists?(user: current_user, host: @host)
    @review = Review.new
  else
    redirect_to @host, notice: "You already posted a review for this host!"
  end
end