protected Method

Base.redirect_to(options = {}, response_status = {})

Redirects the browser to the target specified in options. This parameter can take one of three forms:

  • Hash - The URL will be generated by calling url_for with the options.
  • Record - The URL will be generated by calling url_for with the options, which will reference a named URL for that record.
  • String starting with protocol:// (like http://) - Is passed straight through as the target for redirection.
  • String not containing a protocol - The current protocol and host is prepended to the string.
  • :back - Back to the page that issued the request. Useful for forms that are triggered from multiple places. Short-hand for redirect_to(request.env["HTTP_REFERER"])

Examples:

redirect_to :action => "show", :id => 5
redirect_to post
redirect_to "http://www.rubyonrails.org"
redirect_to "/images/screenshot.jpg"
redirect_to articles_url
redirect_to :back

The redirection happens as a "302 Moved" header unless otherwise specified.

Examples:

redirect_to post_url(@post), :status=>:found
redirect_to :action=>'atom', :status=>:moved_permanently
redirect_to post_url(@post), :status=>301
redirect_to :action=>'atom', :status=>302

When using redirect_to :back, if there is no referrer, RedirectBackError will be raised. You may specify some fallback behavior for this case by rescuing RedirectBackError.

Source Code

# File action_controller/base.rb, line 1031
def redirect_to(options = {}, response_status = {}) #:doc: 

  if options.is_a?(Hash) && options[:status] 
    status = options.delete(:status) 
  elsif response_status[:status] 
    status = response_status[:status] 
  else 
    status = 302 
  end

  case options
    when %r{^\w+://.*}
      raise DoubleRenderError if performed?
      logger.info("Redirected to #{options}") if logger && logger.info?
      response.redirect(options, interpret_status(status))
      response.redirected_to = options
      @performed_redirect = true

    when String
      redirect_to(request.protocol + request.host_with_port + options, :status=>status)

    when :back
      request.env["HTTP_REFERER"] ? redirect_to(request.env["HTTP_REFERER"], :status=>status) : raise(RedirectBackError)

    when Hash
      redirect_to(url_for(options), :status=>status)
      response.redirected_to = options

    else
      redirect_to(url_for(options), :status=>status)
  end
end
Comments

Have your say
Please use Textile formatting (click here for a cheat sheet). Use <code/> and <pre/> for code samples.
Click here to login with OpenID to to post comments.