Recipe 4.7. Following Actions with Redirects


Problem

Submitting a form in your application calls an action that updates your model. You want this action to redirect to a second action that will handle rendering. This way, when the response is sent, the user will see a new URL; refreshing the page will not re-initiate the first action.

Solution

Call redirect_to, as in the following controller's new action:

app/controllers/password_controller.rb:

class AccountController < ApplicationController      def list   end   def new     @account = Account.new(params[:account])     if @account.save       flash[:notice] = 'Account was successfully created.'       redirect_to :action => 'list'     end   end end

Discussion

The solution defines a new method that attempts to create a new account. If a newly created account is saved successfully, the new method stores a flash notice and calls redirect_to to redirect to the controller's list action.

redirect_to takes an options hash as an argument. Internally, this hash is passed to url_for to create a URL. If it's passed a string that begins with protocol information (e.g., http://), it uses the string as the entire relocation target. Otherwise, it interprets the string as a relative URI. Finally, redirect_to can be passed the symbol :back, which tells the browser to redirect to the referring URL or the contents of request.env["HTTP_REFERER"].

Redirection works by sending the browser an HTTP/1.1 302 Found status code, telling the browser that "the requested resource resides temporarily under a different URI," or simply that it should redirect to the URI supplied in this response. This prevents users from creating duplicate accounts with their refresh button, because refreshing only reloads the list template.

A common question on the rubyonrails mailing list is when to use render, instead of redirect_to. As this solution demonstrates, if you don't want a refresh to re-initiate an action that makes changes to your model, use redirect_to. If you want a search form URL, such as /books/search, to remain the same, even when results of the search are displayed by a new action, use render. (When running in development mode, renders are faster than redirects because they don't reload the environment.)

See Also

  • Section 4.11"




Rails Cookbook
Rails Cookbook (Cookbooks (OReilly))
ISBN: 0596527314
EAN: 2147483647
Year: 2007
Pages: 250
Authors: Rob Orsini

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net