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

Jon*_*atz 3 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
Run Code Online (Sandbox Code Playgroud)

有什么建议?

UPDATE

请求的控制器操作代码:

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
Run Code Online (Sandbox Code Playgroud)

klo*_*ner 7

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

def show
  unless user_formulated_request_properly?
    redirect_to(:action => "index")
    return
  end
  respond_to do |format|
    format.html 
  end
end
Run Code Online (Sandbox Code Playgroud) 如果不明显,你不应该进行任何重定向调用user_formulated_request_properly?,也不应该调用yield.(imho,yield是最过度使用的ruby语言功能)