Rails 中的 redirect_to :back

xulin
·

Rails 4 老办法

以前用redirect_to :back这个方法,实现回退源页面功能,但是这个方法会出现问题: 当HTTP_REFERER不存在(介绍地址)时,有时会出现ActionController::RedirectBackError异常。

Referer

Referer 请求头包含了当前请求页面的来源页面的地址,即表示当前页面是通过此来源页面里的链接进入的。服务端一般使用 Referer 请求头识别访问来源,可能会以此进行统计分析、日志记录以及缓存优化等。

解决方法是用rescue示例代码如下:

class PostsController < ApplicationController
  rescue_from ActionController::RedirectBackError, with: :redirect_to_default

  def publish
    post = Post.find params[:id]
    post.publish!
    redirect_to :back
  end

  private

  def redirect_to_default
    redirect_to root_path #出现错误后跳转到根地址
  end
end

Rails 5 后的改进

在Rails 5中,redirect_to:back已被弃用,而是添加了一个名为redirect_back的新方法。 为了处理HTTP_REFERER不存在的情况,它采用了必需的选项fallback_location


class PostsController < ApplicationController

  def publish
    post = Post.find params[:id]
    post.publish!

    redirect_back(fallback_location: root_path)
  end
end

HTTP_REFERER存在时,这会重定向到HTTP_REFERER,当HTTP-REFERER不存在时,则会重定向到fallback_location指定的值。

1
社区准则 博客 联系 社区 状态
主题