简体   繁体   English

在rescue_from 后redirect_to 不起作用

[英]redirect_to after rescue_from is not working

I am trying to catch a custom error, and redirect to root path after it occurs.我试图捕获一个自定义错误,并在它发生后重定向到根路径。 My code in controller looks like this:我在控制器中的代码如下所示:

class ApplicationController < ActionController::Base
  protect_from_forgery with: :exception
  rescue_from Errors::MyError, :with => :my_error

  private

  def my_error
    redirect_to root_path, alert: "my Error"
  end
end

Redirect is not working, after error occurs I am still at the same page.重定向不起作用,发生错误后我仍然在同一页面上。 What is funny, my server logs shows that I was redirected.有趣的是,我的服务器日志显示我被重定向了。

Redirected to http.....
Completed 302 Found in 1908ms (ActiveRecord: 0.5ms)

What happened?发生了什么? And why redirect havent occur?为什么重定向还没有发生?

When you are doing an AJAX call to your server, the browser expect the response to be in javascript ( you talk to me in the JS language, I answer using JS language too, quite simple ).当你对你的服务器进行 AJAX 调用时,浏览器期望响应是 javascript(你用 JS 语言跟我说话,我也用 JS 语言回答,很简单)。 In your case, you need to test if the request is HTML or Javascript, and use the corresponding redirect:在您的情况下,您需要测试请求是 HTML 还是 Javascript,并使用相应的重定向:

def my_error
  path_to_redirect = root_path

  if request.xhr? # tests if the request comes from an AJAX call
    render :js => "window.location = '#{path_to_redirect}'"
  else
    redirect_to path_to_redirect, alert: "my Error"
  end
end

For more answers about AJAX redirects in Rails: Rails 3: How to "redirect_to" in Ajax call?有关 Rails 中 AJAX 重定向的更多答案: Rails 3: How to "redirect_to" in Ajax call?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM