Correctly doing redirect_to :back in Ruby on Rails

2019-01-12 19:20发布

I'm having a problem with redirect_to :back. Yes, it's referrers.

I often get the exception

(ActionController::RedirectBackError) "No HTTP_REFERER was set in the request to this action, so redirect_to :back could not be called successfully. If this is a test, make sure to specify request.env[\"HTTP_REFERER\"]."

I realize that this is a result of a referrer not being available. Is there a way that, for example, one can set a session variable on each access with the last page visited, and, when HTTP_REFERER is not available, utilize this session variable to redirect to?

7条回答
Viruses.
2楼-- · 2019-01-12 19:50

Maybe it's late but I would like to share my method which also preserve options:

  def redirect_back_or_default(default = root_path, *options)
    tag_options = {}
    options.first.each { |k,v| tag_options[k] = v } unless options.empty?
    redirect_to (request.referer.present? ? :back : default), tag_options
  end

You can use it like:

redirect_back_or_default(some_path, :notice => 'Hello from redirect', :status => 301)
查看更多
登录 后发表回答