Agile Web Development with Rails

Page 72

A CTION M ETHODS

action in a given controller (passing parameters), to a URL (on or off the current server), or to the previous page. Let’s look at these three forms in turn. redirect_to Redirects to an action. redirect_to(:action => ..., options...) Sends a temporary redirection to the browser based on the values in the options hash. The target URL is generated using url_for, so this form of redirect_to has all the smarts of Rails routing code behind it. See Section 21.2, Routing Requests, on page 426 for a description. redirect_to Redirects to a URL. redirect_to(path) Redirects to the given path. If the path does not start with a protocol (such as http://), the protocol and port of the current request will be prepended. This method does not perform any rewriting on the URL, so it should not be used to create paths that are intended to link to actions in the application (unless you generate the path using url_for or a named route URL generator). def save order = Order.new(params[:order]) if order.save redirect_to :action => "display" else session[:error_count] ||= 0 session[:error_count] += 1 if session[:error_count] < 4 flash[:notice] = "Please try again" else # Give up -- user is clearly struggling redirect_to("/help/order_entry.html" ) end end end

redirect_to Redirects to the referrer. redirect_to(:back) Redirects to the URL given by the HTTP_REFERER header in the current request. def save_details unless params[:are_you_sure] == 'Y' redirect_to(:back) else ... end end Report erratum

Prepared exclusively for Bill Trammel

this copy is (P1.0 printing, March 2009)

472


Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.