为什么会出现双重渲染错误?

时间:2011-08-25 20:06:38

标签: ruby-on-rails

在我的rails应用程序突然间,我不断得到双重渲染错误(Render and/or redirect were called multiple times in this action. Please note that you may only call render OR redirect, and at mos ....etc...),我不能在我的生活中找出双渲染的位置。当用户输入的查询格式不正确时,就会出现这种情况。以下是检查格式并显示错误的代码:

 def if_user_formulated_request_properly
    unless request.post?
      flash[:error] = "This page can only be accessed through the search page. (POST request only)"
      redirect_to(:action => "index") and return
    end
    if params[:query].blank?
      flash[:error] = "Search criteria can not be blank"
      redirect_to(:action => "index") and return
    end
    if !(params[:query] =~ /-/)
      flash[:error] = %( Format of search criteria is wrong.<br /> Should be [IXLSpecClass value][year]-[Message ID] for example GP07-8)
      redirect_to(:action => "index") and return
    end

    if !(QueryParser.expression.match(params[:query]))
      flash[:error] = %( Format of search criteria is wrong.<br /> Should be [IXLSpecClass value][year]-[Message ID] for example GP07-8)
      redirect_to(:action => "index") and return
    end

有什么建议吗?

更新

请求的控制器操作代码:

def show
  if_user_formulated_request_properly do
    @input_messages = InputMessage.search_by(params[:query].strip) unless params[:query].blank?
  end
  respond_to do |format|
    format.html #default rendering
  end
end

2 个答案:

答案 0 :(得分:7)

我建议对动作代码进行重构,然后让你重构其余部分。 。 。

def show
  unless user_formulated_request_properly?
    redirect_to(:action => "index")
    return
  end
  respond_to do |format|
    format.html 
  end
end
如果不是很明显,你不应该在user_formulated_request_properly?中进行任何重定向调用,也不应该调用yield。 (imho,yield是过度使用的红宝石语言特征)

答案 1 :(得分:2)

我对你的代码做了一些假设。

假设if_user_formulated_request_properly不是控制器的操作,则控制器操作正在调用此方法。当您执行返回时,退出if_user_formulated_request_properly,但控制将返回到操作方法中的代码。

我认为你期望它从动作方法返回,但事实并非如此。相反,它会转到操作中的下一行。

相关问题