【问题标题】:Why is this double render error appearing?为什么会出现这种双重渲染错误?
【发布时间】:2013-02-08 20:32:57
【问题描述】:

突然在我的 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

【问题讨论】:

  • 你总是重定向到同一个动作,你为什么重复这些行?
  • @apneadivin 因为每一行显示不同的错误信息
  • 是的,但这并不妨碍您将redirect_to 放在操作的最后。
  • @apneadiving 否,因为它仅在出现错误时重定向。如果没有错误,什么都不会发生
  • redirect_to (:action =&gt; "index") and return if flash[:error]怎么样

标签: ruby-on-rails


【解决方案1】:

我会建议对操作代码进行重构,并留给您重构其余部分。 . .

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。 (恕我直言,yield 是最过度使用的 ruby​​ 语言功能)

【讨论】:

    【解决方案2】:

    我正在对您的代码做出一些假设。

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

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

    【讨论】:

    • 你猜对了!但只有在没有错误的情况下才会进入下一行。如果有,它应该停在那里并重定向。相反,它显示双重渲染错误
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-29
    • 2019-09-17
    • 2015-10-27
    • 2011-07-05
    相关资源
    最近更新 更多