rescue_from无效后redirect_to

时间:2015-10-21 13:31:36

标签: ruby-on-rails ruby ruby-on-rails-4

我正在尝试捕获自定义错误,并在发生后重定向到根路径。我在控制器中的代码如下所示:

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

重定向不起作用,发生错误后我仍然在同一页面。有趣的是,我的服务器日志显示我被重定向。

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

发生什么事了?为什么没有重定向?

1 个答案:

答案 0 :(得分:0)

当您对服务器进行AJAX调用时,浏览器希望响应是javascript(您在JS语言中与我交谈,我也使用JS语言回答,非常简单)。在您的情况下,您需要测试请求是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

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

相关问题