<divclass="paragraph"><p>In this guide you will learn how controllers work and how they fit into the request cycle in your application. After reading this guide, you will be able to:</p></div>
<divclass="paragraph"><p>Action Controller is the C in MVC. After routing has determined which controller to use for a request, your controller is responsible for making sense of the request and producing the appropriate output. Luckily, Action Controller does most of the groundwork for you and uses smart conventions to make this as straight-forward as possible.</p></div>
<divclass="paragraph"><p>For most conventional RESTful applications, the controller will receive the request (this is invisible to you as the developer), fetch or save data from a model and use a view to create HTML output. If your controller needs to do things a little differently, that’s not a problem, this is just the most common way for a controller to work.</p></div>
<divclass="paragraph"><p>A controller can thus be thought of as a middle man between models and views. It makes the model data available to the view so it can display that data to the user, and it saves or updates data from the user to the model.</p></div>
<divclass="paragraph"><p>A controller is a Ruby class which inherits from ApplicationController and has methods just like any other class. When your application receives a request, the routing will determine which controller and action to run, then Rails creates an instance of that controller and runs the public method with the same name as the action.</p></div>
<divclass="paragraph"><p>There’s no rule saying a method on a controller has to be an action; they may well be used for other purposes such as filters, which will be covered later in this guide.</p></div>
<divclass="paragraph"><p>As an example, if a user goes to <tt>/clients/new</tt> in your application to add a new client, Rails will create an instance of ClientsController and run the <tt>new</tt> method. Note that the empty method from the example above could work just fine because Rails will by default render the <tt>new.html.erb</tt> view unless the action says otherwise. The <tt>new</tt> method could make available to the view a <tt>@client</tt> instance variable by creating a new Client:</p></div>
<divclass="paragraph"><p>The <ahref="../layouts_and_rendering.html">Layouts & rendering guide</a> explains this in more detail.</p></div>
<divclass="paragraph"><p>ApplicationController inherits from ActionController::Base, which defines a number of helpful methods. This guide will cover some of these, but if you’re curious to see what’s in there, you can see all of them in the API documentation or in the source itself.</p></div>
<divclass="paragraph"><p>You will probably want to access data sent in by the user or other parameters in your controller actions. There are two kinds of parameters possible in a web application. The first are parameters that are sent as part of the URL, called query string parameters. The query string is everything after "?" in the URL. The second type of parameter is usually referred to as POST data. This information usually comes from a HTML form which has been filled in by the user. It’s called POST data because it can only be sent as part of an HTTP POST request. Rails does not make any distinction between query string parameters and POST parameters, and both are available in the <tt>params</tt> hash in your controller:</p></div>
<divclass="paragraph"><p>The params hash is not limited to one-dimensional keys and values. It can contain arrays and (nested) hashes. To send an array of values, append "[]" to the key name:</p></div>
<tdclass="content">The actual URL in this example will be encoded as "/clients?ids%5b%5d=1&ids%5b%5d=2&ids%5b%5b=3" as [ and ] are not allowed in URLs. Most of the time you don’t have to worry about this because the browser will take care of it for you, and Rails will decode it back when it receives it, but if you ever find yourself having to send those requests to the server manually you have to keep this in mind.</td>
<divclass="paragraph"><p>The value of <tt>params[:ids]</tt> will now be <tt>["1", "2", "3"]</tt>. Note that parameter values are always strings; Rails makes no attempt to guess or cast the type.</p></div>
<divclass="paragraph"><p>To send a hash you include the key name inside the brackets:</p></div>
<divclass="paragraph"><p>The value of <tt>params[:client]</tt> when this form is submitted will be <tt>{"name" => "Acme", "phone" => "12345", "address" => {"postcode" => "12345", "city" => "Carrot City"}}</tt>. Note the nested hash in <tt>params[:client][:address]</tt>.</p></div>
<divclass="paragraph"><p>Note that the params hash is actually an instance of HashWithIndifferentAccess from Active Support which is a subclass of Hash which lets you use symbols and strings interchangeably as keys.</p></div>
<divclass="paragraph"><p>The <tt>params</tt> hash will always contain the <tt>:controller</tt> and <tt>:action</tt> keys, but you should use the methods <tt>controller_name</tt> and <tt>action_name</tt> instead to access these values. Any other parameters defined by the routing, such as <tt>:id</tt> will also be available. As an example, consider a listing of clients where the list can show either active or inactive clients. We can add a route which captures the <tt>:status</tt> parameter in a "pretty" URL:</p></div>
<divclass="paragraph"><p>In this case, when a user opens the URL <tt>/clients/active</tt>, <tt>params[:status]</tt> will be set to "active". When this route is used, <tt>params[:foo]</tt> will also be set to "bar" just like it was passed in the query string in the same way <tt>params[:action]</tt> will contain "index".</p></div>
<divclass="paragraph"><p>You can set global default parameters that will be used when generating URLs with <tt>default_url_options</tt>. To do this, define a method with that name in your controller:</p></div>
<divclass="paragraph"><p>These options will be used as a starting-point when generating, so it’s possible they’ll be overridden by <tt>url_for</tt>. Because this method is defined in the controller, you can define it on ApplicationController so it would be used for all URL generation, or you could define it on only one controller for all URLs generated there.</p></div>
<divclass="paragraph"><p>Your application has a session for each user in which you can store small amounts of data that will be persisted between requests. The session is only available in the controller and the view and can use one of a number of different storage mechanisms:</p></div>
<divclass="paragraph"><p>All session stores use a cookie - this is required and Rails does not allow any part of the session to be passed in any other way (e.g. you can’t use the query string to pass a session ID) because of security concerns (it’s easier to hijack a session when the ID is part of the URL).</p></div>
<divclass="paragraph"><p>Most stores use a cookie to store the session ID which is then used to look up the session data on the server. The default and recommended store, the CookieStore, does not store session data on the server, but in the cookie itself. The data is cryptographically signed to make it tamper-proof, but it is not encrypted, so anyone with access to it can read its contents but not edit it (Rails will not accept it if it has been edited). It can only store about 4kB of data - much less than the others - but this is usually enough. Storing large amounts of data is discouraged no matter which session store your application uses. You should especially avoid storing complex objects (anything other than basic Ruby objects, the most common example being model instances) in the session, as the server might not be able to reassemble them between requests, which will result in an error. The CookieStore has the added advantage that it does not require any setting up beforehand - Rails will generate a "secret key" which will be used to sign the cookie when you create the application.</p></div>
<divclass="paragraph"><p>Read more about session storage in the <ahref="../security.html">Security Guide</a>.</p></div>
<divclass="paragraph"><p>If you need a different session storage mechanism, you can change it in the <tt>config/environment.rb</tt> file:</p></div>
<divclass="content"><!-- Generator: GNU source-highlight 2.9
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><spanstyle="font-style: italic"><spanstyle="color: #9A1900"># Set to one of [:active_record_store, :drb_store, :mem_cache_store, :cookie_store]</span></span>
<tdclass="content">Sessions are lazily loaded. If you don’t access sessions in your action’s code, they will not be loaded. Hence you will never need to disable sessions, just not accessing them will do the job.</td>
<spanstyle="font-style: italic"><spanstyle="color: #9A1900"># Finds the User with the ID stored in the session with the key :current_user_id</span></span>
<spanstyle="font-style: italic"><spanstyle="color: #9A1900"># This is a common way to handle user login in a Rails application; logging in sets the</span></span>
<divclass="paragraph"><p>To reset the entire session, use <tt>reset_session</tt>.</p></div>
<h3id="_the_flash">4.2. The flash</h3>
<divclass="paragraph"><p>The flash is a special part of the session which is cleared with each request. This means that values stored there will only be available in the next request, which is useful for storing error messages etc. It is accessed in much the same way as the session, like a hash. Let’s use the act of logging out as an example. The controller can send a message which will be displayed to the user on the next request:</p></div>
<divclass="paragraph"><p>The <tt>destroy</tt> action redirects to the application’s <tt>root_url</tt>, where the message will be displayed. Note that it’s entirely up to the next action to decide what, if anything, it will do with what the previous action put in the flash. It’s conventional to display eventual errors or notices from the flash in the application’s layout:</p></div>
<spanstyle="font-style: italic"><spanstyle="color: #9A1900"># Let's say this action corresponds to root_url, but you want all requests here to be redirected to</span></span>
<spanstyle="font-style: italic"><spanstyle="color: #9A1900"># UsersController#index. If an action sets the flash and redirects here, the values would normally be</span></span>
<spanstyle="font-style: italic"><spanstyle="color: #9A1900"># lost when another redirect happens, but you can use keep to make it persist for another request.</span></span>
<spanstyle="font-weight: bold"><spanstyle="color: #0000FF">def</span></span> index
flash<spanstyle="color: #990000">.</span>keep <spanstyle="font-style: italic"><spanstyle="color: #9A1900"># Will persist all flash values. You can also use a key to keep only that value: flash.keep(:notice)</span></span>
<divclass="paragraph"><p>By default, adding values to the flash will make them available to the next request, but sometimes you may want to access those values in the same request. For example, if the <tt>create</tt> action fails to save a resource and you render the <tt>new</tt> template directly, that’s not going to result in a new request, but you may still want to display a message using the flash. To do this, you can use <tt>flash.now</tt> in the same way you use the normal <tt>flash</tt>:</p></div>
flash<spanstyle="color: #990000">.</span>now<spanstyle="color: #990000">[:</span>error<spanstyle="color: #990000">]</span><spanstyle="color: #990000">=</span><spanstyle="color: #FF0000">"Could not save client"</span>
<divclass="paragraph"><p>Your application can store small amounts of data on the client - called cookies - that will be persisted across requests and even sessions. Rails provides easy access to cookies via the <tt>cookies</tt> method, which - much like the <tt>session</tt> - works like a hash:</p></div>
flash<spanstyle="color: #990000">[:</span>notice<spanstyle="color: #990000">]</span><spanstyle="color: #990000">=</span><spanstyle="color: #FF0000">"Thanks for your comment!"</span>
<divclass="paragraph"><p>Note that while for session values you set the key to <tt>nil</tt>, to delete a cookie value you should use <tt>cookies.delete(:key)</tt>.</p></div>
<divclass="paragraph"><p>Filters are methods that are run before, after or "around" a controller action. For example, one filter might check to see if the logged in user has the right credentials to access that particular controller or action. Filters are inherited, so if you set a filter on ApplicationController, it will be run on every controller in your application. A common, simple filter is one which requires that a user is logged in for an action to be run. You can define the filter method this way:</p></div>
flash<spanstyle="color: #990000">[:</span>error<spanstyle="color: #990000">]</span><spanstyle="color: #990000">=</span><spanstyle="color: #FF0000">"You must be logged in to access this section"</span>
redirect_to new_login_url <spanstyle="font-style: italic"><spanstyle="color: #9A1900"># Prevents the current action from running</span></span>
<spanstyle="font-style: italic"><spanstyle="color: #9A1900"># The logged_in? method simply returns true if the user is logged in and</span></span>
<spanstyle="font-style: italic"><spanstyle="color: #9A1900"># false otherwise. It does this by "booleanizing" the current_user method</span></span>
<spanstyle="font-style: italic"><spanstyle="color: #9A1900"># we created previously using a double ! operator. Note that this is not</span></span>
<spanstyle="font-style: italic"><spanstyle="color: #9A1900"># common in Ruby and is discouraged unless you really mean to convert something</span></span>
<spanstyle="font-style: italic"><spanstyle="color: #9A1900"># into true or false.</span></span>
<divclass="paragraph"><p>The method simply stores an error message in the flash and redirects to the login form if the user is not logged in. If a before filter (a filter which is run before the action) renders or redirects, the action will not run. If there are additional filters scheduled to run after the rendering or redirecting filter, they are also cancelled. To use this filter in a controller, use the <tt>before_filter</tt> method:</p></div>
<divclass="paragraph"><p>In this example, the filter is added to ApplicationController and thus all controllers in the application. This will make everything in the application require the user to be logged in in order to use it. For obvious reasons (the user wouldn’t be able to log in in the first place!), not all controllers or actions should require this. You can prevent this filter from running before particular actions with <tt>skip_before_filter</tt>:</p></div>
<divclass="paragraph"><p>Now, the LoginsController’s <tt>new</tt> and <tt>create</tt> actions will work as before without requiring the user to be logged in. The <tt>:only</tt> option is used to only skip this filter for these actions, and there is also an <tt>:except</tt> option which works the other way. These options can be used when adding filters too, so you can add a filter which only runs for selected actions in the first place.</p></div>
<divclass="paragraph"><p>In addition to the before filters, you can run filters after an action has run or both before and after. The after filter is similar to the before filter, but because the action has already been run it has access to the response data that’s about to be sent to the client. Obviously, after filters can not stop the action from running. Around filters are responsible for running the action, but they can choose not to, which is the around filter’s way of stopping it.</p></div>
<divclass="paragraph"><p>While the most common way to use filters is by creating private methods and using *_filter to add them, there are two other ways to do the same thing.</p></div>
<divclass="paragraph"><p>The first is to use a block directly with the *_filter methods. The block receives the controller as an argument, and the <tt>require_login</tt> filter from above could be rewritten to use a block:</p></div>
<divclass="paragraph"><p>Note that the filter in this case uses <tt>send</tt> because the <tt>logged_in?</tt> method is private and the filter is not run in the scope of the controller. This is not the recommended way to implement this particular filter, but in more simple cases it might be useful.</p></div>
<divclass="paragraph"><p>The second way is to use a class (actually, any object that responds to the right methods will do) to handle the filtering. This is useful in cases that are more complex than can not be implemented in a readable and reusable way using the two other methods. As an example, you could rewrite the login filter again to use a class:</p></div>
controller<spanstyle="color: #990000">.</span>flash<spanstyle="color: #990000">[:</span>error<spanstyle="color: #990000">]</span><spanstyle="color: #990000">=</span><spanstyle="color: #FF0000">"You must be logged in to access this section"</span>
<divclass="paragraph"><p>Again, this is not an ideal example for this filter, because it’s not run in the scope of the controller but gets the controller passed as an argument. The filter class has a class method <tt>filter</tt> which gets run before or after the action, depending on if it’s a before or after filter. Classes used as around filters can also use the same <tt>filter</tt> method, which will get run in the same way. The method must <tt>yield</tt> to execute the action. Alternatively, it can have both a <tt>before</tt> and an <tt>after</tt> method that are run before and after the action.</p></div>
<divclass="paragraph"><p>The Rails API documentation has <ahref="http://api.rubyonrails.org/classes/ActionController/Filters/ClassMethods.html">more information on using filters</a>.</p></div>
<divclass="paragraph"><p>Verifications make sure certain criteria are met in order for a controller or action to run. They can specify that a certain key (or several keys in the form of an array) is present in the <tt>params</tt>, <tt>session</tt> or <tt>flash</tt> hashes or that a certain HTTP method was used or that the request was made using XMLHTTPRequest (Ajax). The default action taken when these criteria are not met is to render a 400 Bad Request response, but you can customize this by specifying a redirect URL or rendering something else and you can also add flash messages and HTTP headers to the response. It is described in the <ahref="http://api.rubyonrails.org/classes/ActionController/Verification/ClassMethods.html">API documentation</a> as "essentially a special kind of before_filter".</p></div>
<divclass="paragraph"><p>Here’s an example of using verification to make sure the user supplies a username and a password in order to log in:</p></div>
<divclass="paragraph"><p>Now the <tt>create</tt> action won’t run unless the "username" and "password" parameters are present, and if they’re not, an error message will be added to the flash and the <tt>new</tt> action will be rendered. But there’s something rather important missing from the verification above: It will be used for <strong>every</strong> action in LoginsController, which is not what we want. You can limit which actions it will be used for with the <tt>:only</tt> and <tt>:except</tt> options just like a filter:</p></div>
<spanstyle="color: #990000">:</span>only <spanstyle="color: #990000">=></span><spanstyle="color: #990000">:</span>create <spanstyle="font-style: italic"><spanstyle="color: #9A1900"># Only run this verification for the "create" action</span></span>
<divclass="paragraph"><p>Cross-site request forgery is a type of attack in which a site tricks a user into making requests on another site, possibly adding, modifying or deleting data on that site without the user’s knowledge or permission. The first step to avoid this is to make sure all "destructive" actions (create, update and destroy) can only be accessed with non-GET requests. If you’re following RESTful conventions you’re already doing this. However, a malicious site can still send a non-GET request to your site quite easily, and that’s where the request forgery protection comes in. As the name says, it protects from forged requests. The way this is done is to add a non-guessable token which is only known to your server to each request. This way, if a request comes in without the proper token, it will be denied access.</p></div>
<divclass="paragraph"><p>If you generate a form like this:</p></div>
<divclass="paragraph"><p>Rails adds this token to every form that’s generated using the <ahref="../form_helpers.html">form helpers</a>, so most of the time you don’t have to worry about it. If you’re writing a form manually or need to add the token for another reason, it’s available through the method <tt>form_authenticity_token</tt>:</p></div>
<divclass="paragraph"><p>The <ahref="../security.html">Security Guide</a> has more about this and a lot of other security-related issues that you should be aware of when developing a web application.</p></div>
<divclass="paragraph"><p>In every controller there are two accessor methods pointing to the request and the response objects associated with the request cycle that is currently in execution. The <tt>request</tt> method contains an instance of AbstractRequest and the <tt>response</tt> method returns a <tt>response</tt> object representing what is going to be sent back to the client.</p></div>
<divclass="paragraph"><p>The request object contains a lot of useful information about the request coming in from the client. To get a full list of the available methods, refer to the <ahref="http://api.rubyonrails.org/classes/ActionController/AbstractRequest.html">API documentation</a>. Among the properties that you can access on this object are:</p></div>
<h4id="_tt_path_parameters_tt_tt_query_parameters_tt_and_tt_request_parameters_tt">9.1.1. <tt>path_parameters</tt>, <tt>query_parameters</tt> and <tt>request_parameters</tt></h4>
<divclass="paragraph"><p>Rails collects all of the parameters sent along with the request in the <tt>params</tt> hash, whether they are sent as part of the query string or the post body. The request object has three accessors that give you access to these parameters depending on where they came from. The <tt>query_parameters</tt> hash contains parameters that were sent as part of the query string while the <tt>request_parameters</tt> hash contains parameters sent as part of the post body. The <tt>path_parameters</tt> hash contains parameters that were recognized by the routing as being part of the path leading to this particular controller and action.</p></div>
<divclass="paragraph"><p>The response object is not usually used directly, but is built up during the execution of the action and rendering of the data that is being sent back to the user, but sometimes - like in an after filter - it can be useful to access the response directly. Some of these accessor methods also have setters, allowing you to change their values.</p></div>
<divclass="paragraph"><p>If you want to set custom headers for a response then <tt>response.headers</tt> is the place to do it. The headers attribute is a hash which maps header names to their values, and Rails will set some of them - like "Content-Type" - automatically. If you want to add or change a header, just assign it to <tt>headers</tt> with the name and value:</p></div>
<divclass="paragraph"><p>HTTP Basic authentication is an authentication scheme that is supported by the majority of browsers and other HTTP clients. As an example, consider an administration section which will only be available by entering a username and a password into the browser’s HTTP Basic dialog window. Using the built-in authentication is quite easy and only requires you to use one method, <tt>authenticate_or_request_with_http_basic</tt>.</p></div>
<divclass="paragraph"><p>With this in place, you can create namespaced controllers that inherit from AdminController. The before filter will thus be run for all actions in those controllers, protecting them with HTTP Basic authentication.</p></div>
<divclass="paragraph"><p>HTTP Digest authentication is superior to the Basic authentication as it does not require the client to send unencrypted password over the network. Using Digest authentication with Rails is quite easy and only requires using one method, <tt>authenticate_or_request_with_http_digest</tt>.</p></div>
<divclass="listingblock">
<divclass="content"><!-- Generator: GNU source-highlight 2.9
<divclass="paragraph"><p>As seen in the example above, <tt>authenticate_or_request_with_http_digest</tt> block takes only one argument - the username. And the block returns the password. Returning <tt>false</tt> or <tt>nil</tt> from the <tt>authenticate_or_request_with_http_digest</tt> will cause authentication failure.</p></div>
<divclass="paragraph"><p>Sometimes you may want to send a file to the user instead of rendering an HTML page. All controllers in Rails have the <tt>send_data</tt> and the <tt>send_file</tt> methods, that will both stream data to the client. <tt>send_file</tt> is a convenience method which lets you provide the name of a file on the disk and it will stream the contents of that file for you.</p></div>
<divclass="paragraph"><p>To stream data to the client, use <tt>send_data</tt>:</p></div>
<divclass="paragraph"><p>The <tt>download_pdf</tt> action in the example above will call a private method which actually generates the file (a PDF document) and returns it as a string. This string will then be streamed to the client as a file download and a filename will be suggested to the user. Sometimes when streaming files to the user, you may not want them to download the file. Take images, for example, which can be embedded into HTML pages. To tell the browser a file is not meant to be downloaded, you can set the <tt>:disposition</tt> option to "inline". The opposite and default value for this option is "attachment".</p></div>
<divclass="paragraph"><p>If you want to send a file that already exists on disk, use the <tt>send_file</tt> method. This is usually not recommended, but can be useful if you want to perform some authentication before letting the user download the file.</p></div>
<divclass="paragraph"><p>This will read and stream the file 4Kb at the time, avoiding loading the entire file into memory at once. You can turn off streaming with the <tt>:stream</tt> option or adjust the block size with the <tt>:buffer_size</tt> option.</p></div>
<tdclass="content">Be careful when using (or just don’t use) "outside" data (params, cookies, etc) to locate the file on disk, as this is a security risk that might allow someone to gain access to files they are not meant to see.</td>
<tdclass="content">It is not recommended that you stream static files through Rails if you can instead keep them in a public folder on your web server. It is much more efficient to let the user download the file directly using Apache or another web server, keeping the request from unnecessarily going through the whole Rails stack. Although if you do need the request to go through Rails for some reason, you can set the <tt>:x_sendfile</tt> option to true, and Rails will let the web server handle sending the file to the user, freeing up the Rails process to do other things. Note that your web server needs to support the <tt>X-Sendfile</tt> header for this to work, and you still have to be careful not to use user input in a way that lets someone retrieve arbitrary files.</td>
<divclass="paragraph"><p>While <tt>send_data</tt> works just fine, if you are creating a RESTful application having separate actions for file downloads is usually not necessary. In REST terminology, the PDF file from the example above can be considered just another representation of the client resource. Rails provides an easy and quite sleek way of doing "RESTful downloads". Here’s how you can rewrite the example so that the PDF download is a part of the <tt>show</tt> action, without any streaming:</p></div>
<divclass="paragraph"><p>In order for this example to work, you have to add the PDF MIME type to Rails. This can be done by adding the following line to the file <tt>config/initializers/mime_types.rb</tt>:</p></div>
<tdclass="content">Configuration files are not reloaded on each request, so you have to restart the server in order for their changes to take effect.</td>
<divclass="paragraph"><p>Rails keeps a log file for each environment (development, test and production) in the <tt>log</tt> folder. These are extremely useful when debugging what’s actually going on in your application, but in a live application you may not want every bit of information to be stored in the log file. The <tt>filter_parameter_logging</tt> method can be used to filter out sensitive information from the log. It works by replacing certain values in the <tt>params</tt> hash with "[FILTERED]" as they are written to the log. As an example, let’s see how to filter all parameters with keys that include "password":</p></div>
<divclass="paragraph"><p>The method works recursively through all levels of the params hash and takes an optional second parameter which is used as the replacement string if present. It can also take a block which receives each key in turn and replaces those for which the block returns true.</p></div>
<divclass="paragraph"><p>Most likely your application is going to contain bugs or otherwise throw an exception that needs to be handled. For example, if the user follows a link to a resource that no longer exists in the database, Active Record will throw the ActiveRecord::RecordNotFound exception. Rails' default exception handling displays a 500 Server Error message for all exceptions. If the request was made locally, a nice traceback and some added information gets displayed so you can figure out what went wrong and deal with it. If the request was remote Rails will just display a simple "500 Server Error" message to the user, or a "404 Not Found" if there was a routing error or a record could not be found. Sometimes you might want to customize how these errors are caught and how they’re displayed to the user. There are several levels of exception handling available in a Rails application:</p></div>
<divclass="paragraph"><p>By default a production application will render either a 404 or a 500 error message. These messages are contained in static HTML files in the <tt>public</tt> folder, in <tt>404.html</tt> and <tt>500.html</tt> respectively. You can customize these files to add some extra information and layout, but remember that they are static; i.e. you can’t use RHTML or layouts in them, just plain HTML.</p></div>
<divclass="paragraph"><p>If you want to do something a bit more elaborate when catching errors, you can use <tt>rescue_from</tt>, which handles exceptions of a certain type (or multiple types) in an entire controller and its subclasses. When an exception occurs which is caught by a <tt>rescue_from</tt> directive, the exception object is passed to the handler. The handler can be a method or a Proc object passed to the <tt>:with</tt> option. You can also use a block directly instead of an explicit Proc object.</p></div>
<divclass="paragraph"><p>Here’s how you can use <tt>rescue_from</tt> to intercept all ActiveRecord::RecordNotFound errors and do something with them.</p></div>
<divclass="paragraph"><p>Of course, this example is anything but elaborate and doesn’t improve on the default exception handling at all, but once you can catch all those exceptions you’re free to do whatever you want with them. For example, you could create custom exception classes that will be thrown when a user doesn’t have access to a certain section of your application:</p></div>
flash<spanstyle="color: #990000">[:</span>error<spanstyle="color: #990000">]</span><spanstyle="color: #990000">=</span><spanstyle="color: #FF0000">"You don't have access to this section."</span>
<tdclass="content">Certain exceptions are only rescuable from the ApplicationController class, as they are raised before the controller gets initialized and the action gets executed. See Pratik Naik’s <ahref="http://m.onkey.org/2008/7/20/rescue-from-dispatching">article</a> on the subject for more information.</td>