Froze rails gems
[depot.git] / vendor / rails / railties / doc / guides / html / actioncontroller_basics.html
1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
2 <html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
3 <head>
4 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
5 <title>Action Controller basics</title>
6 <!--[if lt IE 8]>
7 <script src="http://ie7-js.googlecode.com/svn/version/2.0(beta3)/IE8.js" type="text/javascript"></script>
8 <![endif]-->
9 <link href="stylesheets/base.css" media="screen" rel="Stylesheet" type="text/css" />
10 <link href="stylesheets/forms.css" media="screen" rel="Stylesheet" type="text/css" />
11 <link href="stylesheets/more.css" media="screen" rel="Stylesheet" type="text/css" />
12 <style type="text/css">
13 div#container {
14 max-width: 900px;
15 padding-bottom: 3em;
16 }
17
18 div#content {
19 margin-left: 200px;
20 }
21
22 div#container.notoc {
23 max-width: 600px;
24 }
25
26 .notoc div#content {
27 margin-left: 0;
28 }
29
30 pre {
31 line-height: 1.4em;
32 }
33
34 #content p tt {
35 background: #eeeeee;
36 border: solid 1px #cccccc;
37 padding: 3px;
38 }
39
40 dt {
41 font-weight: bold;
42 }
43
44 #content dt tt {
45 font-size: 10pt;
46 }
47
48 dd {
49 margin-left: 3em;
50 }
51
52 #content dt tt, #content pre tt {
53 background: none;
54 padding: 0;
55 border: 0;
56 }
57
58 #content .olist ol {
59 margin-left: 2em;
60 }
61
62 #header {
63 position: relative;
64 max-width: 840px;
65 margin-left: auto;
66 margin-right: auto;
67 }
68
69 #header.notoc {
70 max-width: 580px;
71 }
72
73 #logo {
74 position: absolute;
75 left: 10px;
76 top: 10px;
77 width: 110px;
78 height: 140px;
79 }
80
81 div#header h1#site_title {
82 background: url('images/ruby_on_rails_by_mike_rundle2.gif') top left no-repeat;
83 position: absolute;
84 width: 392px;
85 height: 55px;
86 left: 145px;
87 top: 20px;
88 margin: 0;
89 padding: 0;
90 }
91
92 #site_title span {
93 display: none;
94 }
95
96 #site_title_tagline {
97 display: none;
98 }
99
100 ul#navMain {
101 position: absolute;
102 margin: 0;
103 padding: 0;
104 top: 97px;
105 left: 145px;
106 }
107
108 .left-floaty, .right-floaty {
109 padding: 15px;
110 }
111
112 .admonitionblock,
113 .tableblock {
114 margin-left: 1em;
115 margin-right: 1em;
116 margin-top: 0.25em;
117 margin-bottom: 1em;
118 }
119
120 .admonitionblock .icon {
121 padding-right: 8px;
122 }
123
124 .admonitionblock .content {
125 border: solid 1px #ffda78;
126 background: #fffebd;
127 padding: 10px;
128 padding-top: 8px;
129 padding-bottom: 8px;
130 }
131
132 .admonitionblock .title {
133 font-size: 140%;
134 margin-bottom: 0.5em;
135 }
136
137 .tableblock table {
138 border: solid 1px #aaaaff;
139 background: #f0f0ff;
140 }
141
142 .tableblock th {
143 background: #e0e0e0;
144 }
145
146 .tableblock th,
147 .tableblock td {
148 padding: 3px;
149 padding-left: 5px;
150 padding-right: 5px;
151 }
152
153 .sidebarblock {
154 margin-top: 0.25em;
155 margin: 1em;
156 border: solid 1px #ccccbb;
157 padding: 8px;
158 background: #ffffe0;
159 }
160
161 .sidebarblock .sidebar-title {
162 font-size: 140%;
163 font-weight: 600;
164 margin-bottom: 0.3em;
165 }
166
167 .sidebarblock .sidebar-content > .para:last-child > p {
168 margin-bottom: 0;
169 }
170
171 .sidebarblock .sidebar-title a {
172 text-decoration: none;
173 }
174
175 .sidebarblock .sidebar-title a:hover {
176 text-decoration: underline;
177 }
178
179 </style>
180 </head>
181 <body>
182 <div id="header" >
183 <div id="logo">
184 <a href="index.html" title="Ruby on Rails"><img src="images/rails_logo_remix.gif" alt="Rails" height="140" width="110" /></a>
185 </div>
186
187 <h1 id="site_title"><span>Ruby on Rails</span></h1>
188 <h2 id="site_title_tagline">Sustainable productivity for web-application development</h2>
189
190 <ul id="navMain">
191 <li class="first-child"><a href="http://www.rubyonrails.org/" title="Ruby on Rails" class="ruby_on_rails">Ruby on Rails</a></li>
192 <li><a class="manuals" href="index.html" title="Manuals Index">Guides Index</a></li>
193 </ul>
194 </div>
195
196 <div id="container">
197
198 <div id="sidebar">
199 <h2>Chapters</h2>
200 <ol>
201 <li>
202 <a href="#_what_does_a_controller_do">What Does a Controller do?</a>
203 </li>
204 <li>
205 <a href="#_methods_and_actions">Methods and Actions</a>
206 </li>
207 <li>
208 <a href="#_parameters">Parameters</a>
209 <ul>
210
211 <li><a href="#_hash_and_array_parameters">Hash and Array Parameters</a></li>
212
213 <li><a href="#_routing_parameters">Routing Parameters</a></li>
214
215 <li><a href="#_tt_default_url_options_tt"><tt>default_url_options</tt></a></li>
216
217 </ul>
218 </li>
219 <li>
220 <a href="#_session">Session</a>
221 <ul>
222
223 <li><a href="#_disabling_the_session">Disabling the Session</a></li>
224
225 <li><a href="#_accessing_the_session">Accessing the Session</a></li>
226
227 <li><a href="#_the_flash">The flash</a></li>
228
229 </ul>
230 </li>
231 <li>
232 <a href="#_cookies">Cookies</a>
233 </li>
234 <li>
235 <a href="#_filters">Filters</a>
236 <ul>
237
238 <li><a href="#_after_filters_and_around_filters">After Filters and Around Filters</a></li>
239
240 <li><a href="#_other_ways_to_use_filters">Other Ways to Use Filters</a></li>
241
242 </ul>
243 </li>
244 <li>
245 <a href="#_verification">Verification</a>
246 </li>
247 <li>
248 <a href="#_request_forgery_protection">Request Forgery Protection</a>
249 </li>
250 <li>
251 <a href="#_the_tt_request_tt_and_tt_response_tt_objects">The <tt>request</tt> and <tt>response</tt> Objects</a>
252 <ul>
253
254 <li><a href="#_the_tt_request_tt_object">The <tt>request</tt> Object</a></li>
255
256 <li><a href="#_the_tt_response_tt_object">The <tt>response</tt> Object</a></li>
257
258 </ul>
259 </li>
260 <li>
261 <a href="#_http_basic_authentication">HTTP Basic Authentication</a>
262 </li>
263 <li>
264 <a href="#_streaming_and_file_downloads">Streaming and File Downloads</a>
265 <ul>
266
267 <li><a href="#_sending_files">Sending Files</a></li>
268
269 <li><a href="#_restful_downloads">RESTful Downloads</a></li>
270
271 </ul>
272 </li>
273 <li>
274 <a href="#_parameter_filtering">Parameter Filtering</a>
275 </li>
276 <li>
277 <a href="#_rescue">Rescue</a>
278 <ul>
279
280 <li><a href="#_the_default_500_and_404_templates">The Default 500 and 404 Templates</a></li>
281
282 <li><a href="#_tt_rescue_from_tt"><tt>rescue_from</tt></a></li>
283
284 </ul>
285 </li>
286 <li>
287 <a href="#_changelog">Changelog</a>
288 </li>
289 </ol>
290 </div>
291
292 <div id="content">
293 <h1>Action Controller basics</h1>
294 <div id="preamble">
295 <div class="sectionbody">
296 <div class="para"><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>
297 <div class="ilist"><ul>
298 <li>
299 <p>
300 Follow the flow of a request through a controller
301 </p>
302 </li>
303 <li>
304 <p>
305 Understand why and how to store data in the session or cookies
306 </p>
307 </li>
308 <li>
309 <p>
310 Work with filters to execute code during request processing
311 </p>
312 </li>
313 <li>
314 <p>
315 Use Action Controller's built-in HTTP authentication
316 </p>
317 </li>
318 <li>
319 <p>
320 Stream data directly to the user's browser
321 </p>
322 </li>
323 <li>
324 <p>
325 Filter sensitive parameters so they do not appear in the application's log
326 </p>
327 </li>
328 <li>
329 <p>
330 Deal with exceptions that may be raised during request processing
331 </p>
332 </li>
333 </ul></div>
334 </div>
335 </div>
336 <h2 id="_what_does_a_controller_do">1. What Does a Controller do?</h2>
337 <div class="sectionbody">
338 <div class="para"><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>
339 <div class="para"><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>
340 <div class="para"><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>
341 <div class="admonitionblock">
342 <table><tr>
343 <td class="icon">
344 <img src="./images/icons/note.png" alt="Note" />
345 </td>
346 <td class="content">For more details on the routing process, see <a href="../routing_outside_in.html">Rails Routing from the Outside In</a>.</td>
347 </tr></table>
348 </div>
349 </div>
350 <h2 id="_methods_and_actions">2. Methods and Actions</h2>
351 <div class="sectionbody">
352 <div class="para"><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>
353 <div class="listingblock">
354 <div class="content"><!-- Generator: GNU source-highlight 2.9
355 by Lorenzo Bettini
356 http://www.lorenzobettini.it
357 http://www.gnu.org/software/src-highlite -->
358 <pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> ClientsController <span style="color: #990000">&lt;</span> ApplicationController
359
360 <span style="font-style: italic"><span style="color: #9A1900"># Actions are public methods</span></span>
361 <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> new
362 <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
363
364 <span style="font-style: italic"><span style="color: #9A1900"># Action methods are responsible for producing output</span></span>
365 <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> edit
366 <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
367
368 <span style="font-style: italic"><span style="color: #9A1900"># Helper methods are private and can not be used as actions</span></span>
369 private
370
371 <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> foo
372 <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
373
374 <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
375 </tt></pre></div></div>
376 <div class="para"><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>
377 <div class="para"><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>
378 <div class="listingblock">
379 <div class="content"><!-- Generator: GNU source-highlight 2.9
380 by Lorenzo Bettini
381 http://www.lorenzobettini.it
382 http://www.gnu.org/software/src-highlite -->
383 <pre><tt><span style="font-weight: bold"><span style="color: #0000FF">def</span></span> new
384 <span style="color: #009900">@client</span> <span style="color: #990000">=</span> Client<span style="color: #990000">.</span>new
385 <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
386 </tt></pre></div></div>
387 <div class="para"><p>The <a href="../layouts_and_rendering.html">Layouts &amp; rendering guide</a> explains this in more detail.</p></div>
388 <div class="para"><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>
389 </div>
390 <h2 id="_parameters">3. Parameters</h2>
391 <div class="sectionbody">
392 <div class="para"><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>
393 <div class="listingblock">
394 <div class="content"><!-- Generator: GNU source-highlight 2.9
395 by Lorenzo Bettini
396 http://www.lorenzobettini.it
397 http://www.gnu.org/software/src-highlite -->
398 <pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> ClientsController <span style="color: #990000">&lt;</span> ActionController<span style="color: #990000">::</span>Base
399
400 <span style="font-style: italic"><span style="color: #9A1900"># This action uses query string parameters because it gets run by a HTTP</span></span>
401 <span style="font-style: italic"><span style="color: #9A1900"># GET request, but this does not make any difference to the way in which</span></span>
402 <span style="font-style: italic"><span style="color: #9A1900"># the parameters are accessed. The URL for this action would look like this</span></span>
403 <span style="font-style: italic"><span style="color: #9A1900"># in order to list activated clients: /clients?status=activated</span></span>
404 <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> index
405 <span style="font-weight: bold"><span style="color: #0000FF">if</span></span> params<span style="color: #990000">[:</span>status<span style="color: #990000">]</span> <span style="color: #990000">=</span> <span style="color: #FF0000">"activated"</span>
406 <span style="color: #009900">@clients</span> <span style="color: #990000">=</span> Client<span style="color: #990000">.</span>activated
407 <span style="font-weight: bold"><span style="color: #0000FF">else</span></span>
408 <span style="color: #009900">@clients</span> <span style="color: #990000">=</span> Client<span style="color: #990000">.</span>unativated
409 <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
410 <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
411
412 <span style="font-style: italic"><span style="color: #9A1900"># This action uses POST parameters. They are most likely coming from an HTML</span></span>
413 <span style="font-style: italic"><span style="color: #9A1900"># form which the user has submitted. The URL for this RESTful request will</span></span>
414 <span style="font-style: italic"><span style="color: #9A1900"># be "/clients", and the data will be sent as part of the request body.</span></span>
415 <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> create
416 <span style="color: #009900">@client</span> <span style="color: #990000">=</span> Client<span style="color: #990000">.</span>new<span style="color: #990000">(</span>params<span style="color: #990000">[:</span>client<span style="color: #990000">])</span>
417 <span style="font-weight: bold"><span style="color: #0000FF">if</span></span> <span style="color: #009900">@client</span><span style="color: #990000">.</span>save
418 redirect_to <span style="color: #009900">@client</span>
419 <span style="font-weight: bold"><span style="color: #0000FF">else</span></span>
420 <span style="font-style: italic"><span style="color: #9A1900"># This line overrides the default rendering behavior, which would have been</span></span>
421 <span style="font-style: italic"><span style="color: #9A1900"># to render the "create" view.</span></span>
422 render <span style="color: #990000">:</span>action <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">"new"</span>
423 <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
424 <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
425
426 <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
427 </tt></pre></div></div>
428 <h3 id="_hash_and_array_parameters">3.1. Hash and Array Parameters</h3>
429 <div class="para"><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>
430 <div class="listingblock">
431 <div class="content">
432 <pre><tt>GET /clients?ids[]=1&amp;ids[]=2&amp;ids[]=3</tt></pre>
433 </div></div>
434 <div class="admonitionblock">
435 <table><tr>
436 <td class="icon">
437 <img src="./images/icons/note.png" alt="Note" />
438 </td>
439 <td class="content">The actual URL in this example will be encoded as "/clients?ids%5b%5d=1&amp;ids%5b%5d=2&amp;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>
440 </tr></table>
441 </div>
442 <div class="para"><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>
443 <div class="para"><p>To send a hash you include the key name inside the brackets:</p></div>
444 <div class="listingblock">
445 <div class="content">
446 <pre><tt>&lt;form action="/clients" method="post"&gt;
447 &lt;input type="text" name="client[name]" value="Acme" /&gt;
448 &lt;input type="text" name="client[phone]" value="12345" /&gt;
449 &lt;input type="text" name="client[address][postcode]" value="12345" /&gt;
450 &lt;input type="text" name="client[address][city]" value="Carrot City" /&gt;
451 &lt;/form&gt;</tt></pre>
452 </div></div>
453 <div class="para"><p>The value of <tt>params[:client]</tt> when this form is submitted will be <tt>{"name" &#8658; "Acme", "phone" &#8658; "12345", "address" &#8658; {"postcode" &#8658; "12345", "city" &#8658; "Carrot City"}}</tt>. Note the nested hash in <tt>params[:client][:address]</tt>.</p></div>
454 <div class="para"><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>
455 <h3 id="_routing_parameters">3.2. Routing Parameters</h3>
456 <div class="para"><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>
457 <div class="listingblock">
458 <div class="content"><!-- Generator: GNU source-highlight 2.9
459 by Lorenzo Bettini
460 http://www.lorenzobettini.it
461 http://www.gnu.org/software/src-highlite -->
462 <pre><tt><span style="font-style: italic"><span style="color: #9A1900"># ...</span></span>
463 map<span style="color: #990000">.</span>connect <span style="color: #FF0000">"/clients/:status"</span><span style="color: #990000">,</span> <span style="color: #990000">:</span>controller <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">"clients"</span><span style="color: #990000">,</span> <span style="color: #990000">:</span>action <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">"index"</span><span style="color: #990000">,</span> <span style="color: #990000">:</span>foo <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">"bar"</span>
464 <span style="font-style: italic"><span style="color: #9A1900"># ...</span></span>
465 </tt></pre></div></div>
466 <div class="para"><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>
467 <h3 id="_tt_default_url_options_tt">3.3. <tt>default_url_options</tt></h3>
468 <div class="para"><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>
469 <div class="listingblock">
470 <div class="content">
471 <pre><tt>class ApplicationController &lt; ActionController::Base
472
473 #The options parameter is the hash passed in to +url_for+
474 def default_url_options(options)
475 {:locale =&gt; I18n.locale}
476 end
477
478 end</tt></pre>
479 </div></div>
480 <div class="para"><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>
481 </div>
482 <h2 id="_session">4. Session</h2>
483 <div class="sectionbody">
484 <div class="para"><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>
485 <div class="ilist"><ul>
486 <li>
487 <p>
488 CookieStore - Stores everything on the client.
489 </p>
490 </li>
491 <li>
492 <p>
493 DRbStore - Stores the data on a DRb server.
494 </p>
495 </li>
496 <li>
497 <p>
498 MemCacheStore - Stores the data in a memcache.
499 </p>
500 </li>
501 <li>
502 <p>
503 ActiveRecordStore - Stores the data in a database using Active Record.
504 </p>
505 </li>
506 </ul></div>
507 <div class="para"><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>
508 <div class="para"><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>
509 <div class="para"><p>Read more about session storage in the <a href="../security.html">Security Guide</a>.</p></div>
510 <div class="para"><p>If you need a different session storage mechanism, you can change it in the <tt>config/environment.rb</tt> file:</p></div>
511 <div class="listingblock">
512 <div class="content"><!-- Generator: GNU source-highlight 2.9
513 by Lorenzo Bettini
514 http://www.lorenzobettini.it
515 http://www.gnu.org/software/src-highlite -->
516 <pre><tt><span style="font-style: italic"><span style="color: #9A1900"># Set to one of [:active_record_store, :drb_store, :mem_cache_store, :cookie_store]</span></span>
517 config<span style="color: #990000">.</span>action_controller<span style="color: #990000">.</span>session_store <span style="color: #990000">=</span> <span style="color: #990000">:</span>active_record_store
518 </tt></pre></div></div>
519 <h3 id="_disabling_the_session">4.1. Disabling the Session</h3>
520 <div class="para"><p>Sometimes you don't need a session. In this case, you can turn it off to avoid the unnecessary overhead. To do this, use the <tt>session</tt> class method in your controller:</p></div>
521 <div class="listingblock">
522 <div class="content"><!-- Generator: GNU source-highlight 2.9
523 by Lorenzo Bettini
524 http://www.lorenzobettini.it
525 http://www.gnu.org/software/src-highlite -->
526 <pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> ApplicationController <span style="color: #990000">&lt;</span> ActionController<span style="color: #990000">::</span>Base
527 session <span style="color: #990000">:</span>off
528 <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
529 </tt></pre></div></div>
530 <div class="para"><p>You can also turn the session on or off for a single controller:</p></div>
531 <div class="listingblock">
532 <div class="content"><!-- Generator: GNU source-highlight 2.9
533 by Lorenzo Bettini
534 http://www.lorenzobettini.it
535 http://www.gnu.org/software/src-highlite -->
536 <pre><tt><span style="font-style: italic"><span style="color: #9A1900"># The session is turned off by default in ApplicationController, but we</span></span>
537 <span style="font-style: italic"><span style="color: #9A1900"># want to turn it on for log in/out.</span></span>
538 <span style="font-weight: bold"><span style="color: #0000FF">class</span></span> LoginsController <span style="color: #990000">&lt;</span> ActionController<span style="color: #990000">::</span>Base
539 session <span style="color: #990000">:</span>on
540 <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
541 </tt></pre></div></div>
542 <div class="para"><p>Or even for specified actions:</p></div>
543 <div class="listingblock">
544 <div class="content"><!-- Generator: GNU source-highlight 2.9
545 by Lorenzo Bettini
546 http://www.lorenzobettini.it
547 http://www.gnu.org/software/src-highlite -->
548 <pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> ProductsController <span style="color: #990000">&lt;</span> ActionController<span style="color: #990000">::</span>Base
549 session <span style="color: #990000">:</span>on<span style="color: #990000">,</span> <span style="color: #990000">:</span>only <span style="color: #990000">=&gt;</span> <span style="color: #990000">[:</span>create<span style="color: #990000">,</span> <span style="color: #990000">:</span>update<span style="color: #990000">]</span>
550 <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
551 </tt></pre></div></div>
552 <h3 id="_accessing_the_session">4.2. Accessing the Session</h3>
553 <div class="para"><p>In your controller you can access the session through the <tt>session</tt> instance method.</p></div>
554 <div class="admonitionblock">
555 <table><tr>
556 <td class="icon">
557 <img src="./images/icons/note.png" alt="Note" />
558 </td>
559 <td class="content">There are two <tt>session</tt> methods, the class and the instance method. The class method which is described above is used to turn the session on and off while the instance method described below is used to access session values.</td>
560 </tr></table>
561 </div>
562 <div class="para"><p>Session values are stored using key/value pairs like a hash:</p></div>
563 <div class="listingblock">
564 <div class="content"><!-- Generator: GNU source-highlight 2.9
565 by Lorenzo Bettini
566 http://www.lorenzobettini.it
567 http://www.gnu.org/software/src-highlite -->
568 <pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> ApplicationController <span style="color: #990000">&lt;</span> ActionController<span style="color: #990000">::</span>Base
569
570 private
571
572 <span style="font-style: italic"><span style="color: #9A1900"># Finds the User with the ID stored in the session with the key :current_user_id</span></span>
573 <span style="font-style: italic"><span style="color: #9A1900"># This is a common way to handle user login in a Rails application; logging in sets the</span></span>
574 <span style="font-style: italic"><span style="color: #9A1900"># session value and logging out removes it.</span></span>
575 <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> current_user
576 <span style="color: #009900">@_current_user</span> <span style="color: #990000">||=</span> session<span style="color: #990000">[:</span>current_user_id<span style="color: #990000">]</span> <span style="color: #990000">&amp;&amp;</span> User<span style="color: #990000">.</span>find<span style="color: #990000">(</span>session<span style="color: #990000">[:</span>current_user_id<span style="color: #990000">])</span>
577 <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
578
579 <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
580 </tt></pre></div></div>
581 <div class="para"><p>To store something in the session, just assign it to the key like a hash:</p></div>
582 <div class="listingblock">
583 <div class="content"><!-- Generator: GNU source-highlight 2.9
584 by Lorenzo Bettini
585 http://www.lorenzobettini.it
586 http://www.gnu.org/software/src-highlite -->
587 <pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> LoginsController <span style="color: #990000">&lt;</span> ApplicationController
588
589 <span style="font-style: italic"><span style="color: #9A1900"># "Create" a login, aka "log the user in"</span></span>
590 <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> create
591 <span style="font-weight: bold"><span style="color: #0000FF">if</span></span> user <span style="color: #990000">=</span> User<span style="color: #990000">.</span>authenticate<span style="color: #990000">(</span>params<span style="color: #990000">[:</span>username<span style="color: #990000">,</span> params<span style="color: #990000">[:</span>password<span style="color: #990000">])</span>
592 <span style="font-style: italic"><span style="color: #9A1900"># Save the user ID in the session so it can be used in subsequent requests</span></span>
593 session<span style="color: #990000">[:</span>current_user_id<span style="color: #990000">]</span> <span style="color: #990000">=</span> user<span style="color: #990000">.</span>id
594 redirect_to root_url
595 <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
596 <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
597
598 <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
599 </tt></pre></div></div>
600 <div class="para"><p>To remove something from the session, assign that key to be <tt>nil</tt>:</p></div>
601 <div class="listingblock">
602 <div class="content"><!-- Generator: GNU source-highlight 2.9
603 by Lorenzo Bettini
604 http://www.lorenzobettini.it
605 http://www.gnu.org/software/src-highlite -->
606 <pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> LoginsController <span style="color: #990000">&lt;</span> ApplicationController
607
608 <span style="font-style: italic"><span style="color: #9A1900"># "Delete" a login, aka "log the user out"</span></span>
609 <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> destroy
610 <span style="font-style: italic"><span style="color: #9A1900"># Remove the user id from the session</span></span>
611 session<span style="color: #990000">[:</span>current_user_id<span style="color: #990000">]</span> <span style="color: #990000">=</span> <span style="font-weight: bold"><span style="color: #0000FF">nil</span></span>
612 redirect_to root_url
613 <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
614
615 <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
616 </tt></pre></div></div>
617 <div class="para"><p>To reset the entire session, use <tt>reset_session</tt>.</p></div>
618 <h3 id="_the_flash">4.3. The flash</h3>
619 <div class="para"><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>
620 <div class="listingblock">
621 <div class="content"><!-- Generator: GNU source-highlight 2.9
622 by Lorenzo Bettini
623 http://www.lorenzobettini.it
624 http://www.gnu.org/software/src-highlite -->
625 <pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> LoginsController <span style="color: #990000">&lt;</span> ApplicationController
626
627 <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> destroy
628 session<span style="color: #990000">[:</span>current_user_id<span style="color: #990000">]</span> <span style="color: #990000">=</span> <span style="font-weight: bold"><span style="color: #0000FF">nil</span></span>
629 flash<span style="color: #990000">[:</span>notice<span style="color: #990000">]</span> <span style="color: #990000">=</span> <span style="color: #FF0000">"You have successfully logged out"</span>
630 redirect_to root_url
631 <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
632
633 <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
634 </tt></pre></div></div>
635 <div class="para"><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>
636 <div class="listingblock">
637 <div class="content">
638 <pre><tt>&lt;html&gt;
639 &lt;!-- &lt;head/&gt; --&gt;
640 &lt;body&gt;
641 &lt;% if flash[:notice] -%&gt;
642 &lt;p class="notice"&gt;&lt;%= flash[:notice] %&gt;&lt;/p&gt;
643 &lt;% end -%&gt;
644 &lt;% if flash[:error] -%&gt;
645 &lt;p class="error"&gt;&lt;%= flash[:error] %&gt;&lt;/p&gt;
646 &lt;% end -%&gt;
647 &lt;!-- more content --&gt;
648 &lt;/body&gt;
649 &lt;/html&gt;</tt></pre>
650 </div></div>
651 <div class="para"><p>This way, if an action sets an error or a notice message, the layout will display it automatically.</p></div>
652 <div class="para"><p>If you want a flash value to be carried over to another request, use the <tt>keep</tt> method:</p></div>
653 <div class="listingblock">
654 <div class="content"><!-- Generator: GNU source-highlight 2.9
655 by Lorenzo Bettini
656 http://www.lorenzobettini.it
657 http://www.gnu.org/software/src-highlite -->
658 <pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> MainController <span style="color: #990000">&lt;</span> ApplicationController
659
660 <span style="font-style: italic"><span style="color: #9A1900"># Let's say this action corresponds to root_url, but you want all requests here to be redirected to</span></span>
661 <span style="font-style: italic"><span style="color: #9A1900"># UsersController#index. If an action sets the flash and redirects here, the values would normally be</span></span>
662 <span style="font-style: italic"><span style="color: #9A1900"># lost when another redirect happens, but you can use keep to make it persist for another request.</span></span>
663 <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> index
664 flash<span style="color: #990000">.</span>keep <span style="font-style: italic"><span style="color: #9A1900"># Will persist all flash values. You can also use a key to keep only that value: flash.keep(:notice)</span></span>
665 redirect_to users_url
666 <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
667
668 <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
669 </tt></pre></div></div>
670 <h4 id="_tt_flash_now_tt">4.3.1. <tt>flash.now</tt></h4>
671 <div class="para"><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>
672 <div class="listingblock">
673 <div class="content"><!-- Generator: GNU source-highlight 2.9
674 by Lorenzo Bettini
675 http://www.lorenzobettini.it
676 http://www.gnu.org/software/src-highlite -->
677 <pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> ClientsController <span style="color: #990000">&lt;</span> ApplicationController
678
679 <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> create
680 <span style="color: #009900">@client</span> <span style="color: #990000">=</span> Client<span style="color: #990000">.</span>new<span style="color: #990000">(</span>params<span style="color: #990000">[:</span>client<span style="color: #990000">])</span>
681 <span style="font-weight: bold"><span style="color: #0000FF">if</span></span> <span style="color: #009900">@client</span><span style="color: #990000">.</span>save
682 <span style="font-style: italic"><span style="color: #9A1900"># ...</span></span>
683 <span style="font-weight: bold"><span style="color: #0000FF">else</span></span>
684 flash<span style="color: #990000">.</span>now<span style="color: #990000">[:</span>error<span style="color: #990000">]</span> <span style="color: #990000">=</span> <span style="color: #FF0000">"Could not save client"</span>
685 render <span style="color: #990000">:</span>action <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">"new"</span>
686 <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
687 <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
688
689 <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
690 </tt></pre></div></div>
691 </div>
692 <h2 id="_cookies">5. Cookies</h2>
693 <div class="sectionbody">
694 <div class="para"><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>
695 <div class="listingblock">
696 <div class="content"><!-- Generator: GNU source-highlight 2.9
697 by Lorenzo Bettini
698 http://www.lorenzobettini.it
699 http://www.gnu.org/software/src-highlite -->
700 <pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> CommentsController <span style="color: #990000">&lt;</span> ApplicationController
701
702 <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> new
703 <span style="font-style: italic"><span style="color: #9A1900">#Auto-fill the commenter's name if it has been stored in a cookie</span></span>
704 <span style="color: #009900">@comment</span> <span style="color: #990000">=</span> Comment<span style="color: #990000">.</span>new<span style="color: #990000">(:</span>name <span style="color: #990000">=&gt;</span> cookies<span style="color: #990000">[:</span>commenter_name<span style="color: #990000">])</span>
705 <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
706
707 <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> create
708 <span style="color: #009900">@comment</span> <span style="color: #990000">=</span> Comment<span style="color: #990000">.</span>new<span style="color: #990000">(</span>params<span style="color: #990000">[:</span>comment<span style="color: #990000">])</span>
709 <span style="font-weight: bold"><span style="color: #0000FF">if</span></span> <span style="color: #009900">@comment</span><span style="color: #990000">.</span>save
710 flash<span style="color: #990000">[:</span>notice<span style="color: #990000">]</span> <span style="color: #990000">=</span> <span style="color: #FF0000">"Thanks for your comment!"</span>
711 <span style="font-weight: bold"><span style="color: #0000FF">if</span></span> params<span style="color: #990000">[:</span>remember_name<span style="color: #990000">]</span>
712 <span style="font-style: italic"><span style="color: #9A1900"># Remember the commenter's name</span></span>
713 cookies<span style="color: #990000">[:</span>commenter_name<span style="color: #990000">]</span> <span style="color: #990000">=</span> <span style="color: #009900">@comment</span><span style="color: #990000">.</span>name
714 <span style="font-weight: bold"><span style="color: #0000FF">else</span></span>
715 <span style="font-style: italic"><span style="color: #9A1900"># Don't remember, and delete the name if it has been remembered before</span></span>
716 cookies<span style="color: #990000">.</span>delete<span style="color: #990000">(:</span>commenter_name<span style="color: #990000">)</span>
717 <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
718 redirect_to <span style="color: #009900">@comment</span><span style="color: #990000">.</span>article
719 <span style="font-weight: bold"><span style="color: #0000FF">else</span></span>
720 render <span style="color: #990000">:</span>action <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">"new"</span>
721 <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
722 <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
723
724 <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
725 </tt></pre></div></div>
726 <div class="para"><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>
727 </div>
728 <h2 id="_filters">6. Filters</h2>
729 <div class="sectionbody">
730 <div class="para"><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>
731 <div class="listingblock">
732 <div class="content"><!-- Generator: GNU source-highlight 2.9
733 by Lorenzo Bettini
734 http://www.lorenzobettini.it
735 http://www.gnu.org/software/src-highlite -->
736 <pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> ApplicationController <span style="color: #990000">&lt;</span> ActionController<span style="color: #990000">::</span>Base
737
738 private
739
740 <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> require_login
741 <span style="font-weight: bold"><span style="color: #0000FF">unless</span></span> logged_in?
742 flash<span style="color: #990000">[:</span>error<span style="color: #990000">]</span> <span style="color: #990000">=</span> <span style="color: #FF0000">"You must be logged in to access this section"</span>
743 redirect_to new_login_url <span style="font-style: italic"><span style="color: #9A1900"># Prevents the current action from running</span></span>
744 <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
745 <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
746
747 <span style="font-style: italic"><span style="color: #9A1900"># The logged_in? method simply returns true if the user is logged in and</span></span>
748 <span style="font-style: italic"><span style="color: #9A1900"># false otherwise. It does this by "booleanizing" the current_user method</span></span>
749 <span style="font-style: italic"><span style="color: #9A1900"># we created previously using a double ! operator. Note that this is not</span></span>
750 <span style="font-style: italic"><span style="color: #9A1900"># common in Ruby and is discouraged unless you really mean to convert something</span></span>
751 <span style="font-style: italic"><span style="color: #9A1900"># into true or false.</span></span>
752 <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> logged_in?
753 <span style="color: #990000">!!</span>current_user
754 <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
755
756 <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
757 </tt></pre></div></div>
758 <div class="para"><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>
759 <div class="listingblock">
760 <div class="content"><!-- Generator: GNU source-highlight 2.9
761 by Lorenzo Bettini
762 http://www.lorenzobettini.it
763 http://www.gnu.org/software/src-highlite -->
764 <pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> ApplicationController <span style="color: #990000">&lt;</span> ActionController<span style="color: #990000">::</span>Base
765
766 before_filter <span style="color: #990000">:</span>require_login
767
768 <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
769 </tt></pre></div></div>
770 <div class="para"><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>
771 <div class="listingblock">
772 <div class="content"><!-- Generator: GNU source-highlight 2.9
773 by Lorenzo Bettini
774 http://www.lorenzobettini.it
775 http://www.gnu.org/software/src-highlite -->
776 <pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> LoginsController <span style="color: #990000">&lt;</span> Application
777
778 skip_before_filter <span style="color: #990000">:</span>require_login<span style="color: #990000">,</span> <span style="color: #990000">:</span>only <span style="color: #990000">=&gt;</span> <span style="color: #990000">[:</span>new<span style="color: #990000">,</span> <span style="color: #990000">:</span>create<span style="color: #990000">]</span>
779
780 <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
781 </tt></pre></div></div>
782 <div class="para"><p>Now, the <tt>LoginsController</tt>'s "new" and "create" 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>
783 <h3 id="_after_filters_and_around_filters">6.1. After Filters and Around Filters</h3>
784 <div class="para"><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>
785 <div class="listingblock">
786 <div class="content"><!-- Generator: GNU source-highlight 2.9
787 by Lorenzo Bettini
788 http://www.lorenzobettini.it
789 http://www.gnu.org/software/src-highlite -->
790 <pre><tt><span style="font-style: italic"><span style="color: #9A1900"># Example taken from the Rails API filter documentation:</span></span>
791 <span style="font-style: italic"><span style="color: #9A1900"># http://api.rubyonrails.org/classes/ActionController/Filters/ClassMethods.html</span></span>
792 <span style="font-weight: bold"><span style="color: #0000FF">class</span></span> ApplicationController <span style="color: #990000">&lt;</span> Application
793
794 around_filter <span style="color: #990000">:</span>catch_exceptions
795
796 private
797
798 <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> catch_exceptions
799 <span style="font-weight: bold"><span style="color: #0000FF">yield</span></span>
800 <span style="font-weight: bold"><span style="color: #0000FF">rescue</span></span> <span style="color: #990000">=&gt;</span> exception
801 logger<span style="color: #990000">.</span>debug <span style="color: #FF0000">"Caught exception! #{exception}"</span>
802 <span style="font-weight: bold"><span style="color: #0000FF">raise</span></span>
803 <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
804
805 <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
806 </tt></pre></div></div>
807 <h3 id="_other_ways_to_use_filters">6.2. Other Ways to Use Filters</h3>
808 <div class="para"><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>
809 <div class="para"><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>
810 <div class="listingblock">
811 <div class="content"><!-- Generator: GNU source-highlight 2.9
812 by Lorenzo Bettini
813 http://www.lorenzobettini.it
814 http://www.gnu.org/software/src-highlite -->
815 <pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> ApplicationController <span style="color: #990000">&lt;</span> ActionController<span style="color: #990000">::</span>Base
816
817 before_filter <span style="color: #FF0000">{</span> <span style="color: #990000">|</span>controller<span style="color: #990000">|</span> redirect_to new_login_url <span style="font-weight: bold"><span style="color: #0000FF">unless</span></span> controller<span style="color: #990000">.</span>send<span style="color: #990000">(:</span>logged_in?<span style="color: #990000">)</span> <span style="color: #FF0000">}</span>
818
819 <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
820 </tt></pre></div></div>
821 <div class="para"><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>
822 <div class="para"><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>
823 <div class="listingblock">
824 <div class="content"><!-- Generator: GNU source-highlight 2.9
825 by Lorenzo Bettini
826 http://www.lorenzobettini.it
827 http://www.gnu.org/software/src-highlite -->
828 <pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> ApplicationController <span style="color: #990000">&lt;</span> ActionController<span style="color: #990000">::</span>Base
829
830 before_filter LoginFilter
831
832 <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
833
834 <span style="font-weight: bold"><span style="color: #0000FF">class</span></span> LoginFilter
835
836 <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> <span style="font-weight: bold"><span style="color: #0000FF">self</span></span><span style="color: #990000">.</span>filter<span style="color: #990000">(</span>controller<span style="color: #990000">)</span>
837 <span style="font-weight: bold"><span style="color: #0000FF">unless</span></span> logged_in?
838 controller<span style="color: #990000">.</span>flash<span style="color: #990000">[:</span>error<span style="color: #990000">]</span> <span style="color: #990000">=</span> <span style="color: #FF0000">"You must be logged in to access this section"</span>
839 controller<span style="color: #990000">.</span>redirect_to controller<span style="color: #990000">.</span>new_login_url
840 <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
841 <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
842
843 <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
844 </tt></pre></div></div>
845 <div class="para"><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>
846 <div class="para"><p>The Rails API documentation has <a href="http://api.rubyonrails.org/classes/ActionController/Filters/ClassMethods.html">more information on using filters</a>.</p></div>
847 </div>
848 <h2 id="_verification">7. Verification</h2>
849 <div class="sectionbody">
850 <div class="para"><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 <a href="http://api.rubyonrails.org/classes/ActionController/Verification/ClassMethods.html">API documentation</a> as "essentially a special kind of before_filter".</p></div>
851 <div class="para"><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>
852 <div class="listingblock">
853 <div class="content"><!-- Generator: GNU source-highlight 2.9
854 by Lorenzo Bettini
855 http://www.lorenzobettini.it
856 http://www.gnu.org/software/src-highlite -->
857 <pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> LoginsController <span style="color: #990000">&lt;</span> ApplicationController
858
859 verify <span style="color: #990000">:</span>params <span style="color: #990000">=&gt;</span> <span style="color: #990000">[:</span>username<span style="color: #990000">,</span> <span style="color: #990000">:</span>password<span style="color: #990000">],</span>
860 <span style="color: #990000">:</span>render <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">{</span><span style="color: #990000">:</span>action <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">"new"</span><span style="color: #FF0000">}</span><span style="color: #990000">,</span>
861 <span style="color: #990000">:</span>add_flash <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">{</span><span style="color: #990000">:</span>error <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">"Username and password required to log in"</span><span style="color: #FF0000">}</span>
862
863 <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> create
864 <span style="color: #009900">@user</span> <span style="color: #990000">=</span> User<span style="color: #990000">.</span>authenticate<span style="color: #990000">(</span>params<span style="color: #990000">[:</span>username<span style="color: #990000">],</span> params<span style="color: #990000">[:</span>password<span style="color: #990000">])</span>
865 <span style="font-weight: bold"><span style="color: #0000FF">if</span></span> <span style="color: #009900">@user</span>
866 flash<span style="color: #990000">[:</span>notice<span style="color: #990000">]</span> <span style="color: #990000">=</span> <span style="color: #FF0000">"You're logged in"</span>
867 redirect_to root_url
868 <span style="font-weight: bold"><span style="color: #0000FF">else</span></span>
869 render <span style="color: #990000">:</span>action <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">"new"</span>
870 <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
871 <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
872
873 <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
874 </tt></pre></div></div>
875 <div class="para"><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 "new" 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>
876 <div class="listingblock">
877 <div class="content"><!-- Generator: GNU source-highlight 2.9
878 by Lorenzo Bettini
879 http://www.lorenzobettini.it
880 http://www.gnu.org/software/src-highlite -->
881 <pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> LoginsController <span style="color: #990000">&lt;</span> ApplicationController
882
883 verify <span style="color: #990000">:</span>params <span style="color: #990000">=&gt;</span> <span style="color: #990000">[:</span>username<span style="color: #990000">,</span> <span style="color: #990000">:</span>password<span style="color: #990000">],</span>
884 <span style="color: #990000">:</span>render <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">{</span><span style="color: #990000">:</span>action <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">"new"</span><span style="color: #FF0000">}</span><span style="color: #990000">,</span>
885 <span style="color: #990000">:</span>add_flash <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">{</span><span style="color: #990000">:</span>error <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">"Username and password required to log in"</span><span style="color: #FF0000">}</span><span style="color: #990000">,</span>
886 <span style="color: #990000">:</span>only <span style="color: #990000">=&gt;</span> <span style="color: #990000">:</span>create <span style="font-style: italic"><span style="color: #9A1900"># Only run this verification for the "create" action</span></span>
887
888 <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
889 </tt></pre></div></div>
890 </div>
891 <h2 id="_request_forgery_protection">8. Request Forgery Protection</h2>
892 <div class="sectionbody">
893 <div class="para"><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>
894 <div class="para"><p>If you generate a form like this:</p></div>
895 <div class="listingblock">
896 <div class="content"><!-- Generator: GNU source-highlight 2.9
897 by Lorenzo Bettini
898 http://www.lorenzobettini.it
899 http://www.gnu.org/software/src-highlite -->
900 <pre><tt><span style="color: #FF0000">&lt;% form_for @user do |f| -%&gt;</span>
901 <span style="color: #FF0000">&lt;%= f.text_field :username %&gt;</span>
902 <span style="color: #FF0000">&lt;%= f.text_field :password -%&gt;</span>
903 <span style="color: #FF0000">&lt;% end -%&gt;</span>
904 </tt></pre></div></div>
905 <div class="para"><p>You will see how the token gets added as a hidden field:</p></div>
906 <div class="listingblock">
907 <div class="content"><!-- Generator: GNU source-highlight 2.9
908 by Lorenzo Bettini
909 http://www.lorenzobettini.it
910 http://www.gnu.org/software/src-highlite -->
911 <pre><tt><span style="font-weight: bold"><span style="color: #0000FF">&lt;form</span></span> <span style="color: #009900">action</span><span style="color: #990000">=</span><span style="color: #FF0000">"/users/1"</span> <span style="color: #009900">method</span><span style="color: #990000">=</span><span style="color: #FF0000">"post"</span><span style="font-weight: bold"><span style="color: #0000FF">&gt;</span></span>
912 <span style="font-weight: bold"><span style="color: #0000FF">&lt;div&gt;</span></span><span style="font-style: italic"><span style="color: #9A1900">&lt;!-- ... --&gt;</span></span><span style="font-weight: bold"><span style="color: #0000FF">&lt;input</span></span> <span style="color: #009900">type</span><span style="color: #990000">=</span><span style="color: #FF0000">"hidden"</span> <span style="color: #009900">value</span><span style="color: #990000">=</span><span style="color: #FF0000">"67250ab105eb5ad10851c00a5621854a23af5489"</span> <span style="color: #009900">name</span><span style="color: #990000">=</span><span style="color: #FF0000">"authenticity_token"</span><span style="font-weight: bold"><span style="color: #0000FF">/&gt;&lt;/div&gt;</span></span>
913 <span style="font-style: italic"><span style="color: #9A1900">&lt;!-- Fields --&gt;</span></span>
914 <span style="font-weight: bold"><span style="color: #0000FF">&lt;/form&gt;</span></span>
915 </tt></pre></div></div>
916 <div class="para"><p>Rails adds this token to every form that's generated using the <a href="../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>
917 <div class="listingblock">
918 <div class="title">Example: Add a JavaScript variable containing the token for use with Ajax</div>
919 <div class="content">
920 <pre><tt>&lt;%= javascript_tag "MyApp.authenticity_token = '#{form_authenticity_token}'" %&gt;</tt></pre>
921 </div></div>
922 <div class="para"><p>The <a href="../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>
923 </div>
924 <h2 id="_the_tt_request_tt_and_tt_response_tt_objects">9. The <tt>request</tt> and <tt>response</tt> Objects</h2>
925 <div class="sectionbody">
926 <div class="para"><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>
927 <h3 id="_the_tt_request_tt_object">9.1. The <tt>request</tt> Object</h3>
928 <div class="para"><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 <a href="http://api.rubyonrails.org/classes/ActionController/AbstractRequest.html">API documentation</a>. Among the properties that you can access on this object are:</p></div>
929 <div class="ilist"><ul>
930 <li>
931 <p>
932 host - The hostname used for this request.
933 </p>
934 </li>
935 <li>
936 <p>
937 domain - The hostname without the first segment (usually "www").
938 </p>
939 </li>
940 <li>
941 <p>
942 format - The content type requested by the client.
943 </p>
944 </li>
945 <li>
946 <p>
947 method - The HTTP method used for the request.
948 </p>
949 </li>
950 <li>
951 <p>
952 get?, post?, put?, delete?, head? - Returns true if the HTTP method is get/post/put/delete/head.
953 </p>
954 </li>
955 <li>
956 <p>
957 headers - Returns a hash containing the headers associated with the request.
958 </p>
959 </li>
960 <li>
961 <p>
962 port - The port number (integer) used for the request.
963 </p>
964 </li>
965 <li>
966 <p>
967 protocol - The protocol used for the request.
968 </p>
969 </li>
970 <li>
971 <p>
972 query_string - The query string part of the URL - everything after "?".
973 </p>
974 </li>
975 <li>
976 <p>
977 remote_ip - The IP address of the client.
978 </p>
979 </li>
980 <li>
981 <p>
982 url - The entire URL used for the request.
983 </p>
984 </li>
985 </ul></div>
986 <h4 id="_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>
987 <div class="para"><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>
988 <h3 id="_the_tt_response_tt_object">9.2. The <tt>response</tt> Object</h3>
989 <div class="para"><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>
990 <div class="ilist"><ul>
991 <li>
992 <p>
993 body - This is the string of data being sent back to the client. This is most often HTML.
994 </p>
995 </li>
996 <li>
997 <p>
998 status - The HTTP status code for the response, like 200 for a successful request or 404 for file not found.
999 </p>
1000 </li>
1001 <li>
1002 <p>
1003 location - The URL the client is being redirected to, if any.
1004 </p>
1005 </li>
1006 <li>
1007 <p>
1008 content_type - The content type of the response.
1009 </p>
1010 </li>
1011 <li>
1012 <p>
1013 charset - The character set being used for the response. Default is "utf8".
1014 </p>
1015 </li>
1016 <li>
1017 <p>
1018 headers - Headers used for the response.
1019 </p>
1020 </li>
1021 </ul></div>
1022 <h4 id="_setting_custom_headers">9.2.1. Setting Custom Headers</h4>
1023 <div class="para"><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>
1024 <div class="listingblock">
1025 <div class="content"><!-- Generator: GNU source-highlight 2.9
1026 by Lorenzo Bettini
1027 http://www.lorenzobettini.it
1028 http://www.gnu.org/software/src-highlite -->
1029 <pre><tt>response<span style="color: #990000">.</span>headers<span style="color: #990000">[</span><span style="color: #FF0000">"Content-Type"</span><span style="color: #990000">]</span> <span style="color: #990000">=</span> <span style="color: #FF0000">"application/pdf"</span>
1030 </tt></pre></div></div>
1031 </div>
1032 <h2 id="_http_basic_authentication">10. HTTP Basic Authentication</h2>
1033 <div class="sectionbody">
1034 <div class="para"><p>Rails comes with built-in HTTP Basic authentication. This 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>
1035 <div class="listingblock">
1036 <div class="content"><!-- Generator: GNU source-highlight 2.9
1037 by Lorenzo Bettini
1038 http://www.lorenzobettini.it
1039 http://www.gnu.org/software/src-highlite -->
1040 <pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> AdminController <span style="color: #990000">&lt;</span> ApplicationController
1041
1042 USERNAME<span style="color: #990000">,</span> PASSWORD <span style="color: #990000">=</span> <span style="color: #FF0000">"humbaba"</span><span style="color: #990000">,</span> <span style="color: #FF0000">"5baa61e4c9b93f3f0682250b6cf8331b7ee68fd8"</span>
1043
1044 before_filter <span style="color: #990000">:</span>authenticate
1045
1046 private
1047
1048 <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> authenticate
1049 authenticate_or_request_with_http_basic <span style="font-weight: bold"><span style="color: #0000FF">do</span></span> <span style="color: #990000">|</span>username<span style="color: #990000">,</span> password<span style="color: #990000">|</span>
1050 username <span style="color: #990000">==</span> USERNAME <span style="color: #990000">&amp;&amp;</span> Digest<span style="color: #990000">::</span>SHA1<span style="color: #990000">.</span>hexdigest<span style="color: #990000">(</span>password<span style="color: #990000">)</span> <span style="color: #990000">==</span> PASSWORD
1051 <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
1052 <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
1053
1054 <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
1055 </tt></pre></div></div>
1056 <div class="para"><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>
1057 </div>
1058 <h2 id="_streaming_and_file_downloads">11. Streaming and File Downloads</h2>
1059 <div class="sectionbody">
1060 <div class="para"><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>
1061 <div class="para"><p>To stream data to the client, use <tt>send_data</tt>:</p></div>
1062 <div class="listingblock">
1063 <div class="content"><!-- Generator: GNU source-highlight 2.9
1064 by Lorenzo Bettini
1065 http://www.lorenzobettini.it
1066 http://www.gnu.org/software/src-highlite -->
1067 <pre><tt><span style="font-weight: bold"><span style="color: #000080">require</span></span> <span style="color: #FF0000">"prawn"</span>
1068 <span style="font-weight: bold"><span style="color: #0000FF">class</span></span> ClientsController <span style="color: #990000">&lt;</span> ApplicationController
1069
1070 <span style="font-style: italic"><span style="color: #9A1900"># Generate a PDF document with information on the client and return it.</span></span>
1071 <span style="font-style: italic"><span style="color: #9A1900"># The user will get the PDF as a file download.</span></span>
1072 <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> download_pdf
1073 client <span style="color: #990000">=</span> Client<span style="color: #990000">.</span>find<span style="color: #990000">(</span>params<span style="color: #990000">[:</span>id<span style="color: #990000">])</span>
1074 send_data<span style="color: #990000">(</span>generate_pdf<span style="color: #990000">,</span> <span style="color: #990000">:</span>filename <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">"#{client.name}.pdf"</span><span style="color: #990000">,</span> <span style="color: #990000">:</span>type <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">"application/pdf"</span><span style="color: #990000">)</span>
1075 <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
1076
1077 private
1078
1079 <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> generate_pdf<span style="color: #990000">(</span>client<span style="color: #990000">)</span>
1080 Prawn<span style="color: #990000">::</span>Document<span style="color: #990000">.</span>new <span style="font-weight: bold"><span style="color: #0000FF">do</span></span>
1081 text client<span style="color: #990000">.</span>name<span style="color: #990000">,</span> <span style="color: #990000">:</span>align <span style="color: #990000">=&gt;</span> <span style="color: #990000">:</span>center
1082 text <span style="color: #FF0000">"Address: #{client.address}"</span>
1083 text <span style="color: #FF0000">"Email: #{client.email}"</span>
1084 <span style="font-weight: bold"><span style="color: #0000FF">end</span></span><span style="color: #990000">.</span>render
1085 <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
1086
1087 <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
1088 </tt></pre></div></div>
1089 <div class="para"><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>
1090 <h3 id="_sending_files">11.1. Sending Files</h3>
1091 <div class="para"><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>
1092 <div class="listingblock">
1093 <div class="content"><!-- Generator: GNU source-highlight 2.9
1094 by Lorenzo Bettini
1095 http://www.lorenzobettini.it
1096 http://www.gnu.org/software/src-highlite -->
1097 <pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> ClientsController <span style="color: #990000">&lt;</span> ApplicationController
1098
1099 <span style="font-style: italic"><span style="color: #9A1900"># Stream a file that has already been generated and stored on disk</span></span>
1100 <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> download_pdf
1101 client <span style="color: #990000">=</span> Client<span style="color: #990000">.</span>find<span style="color: #990000">(</span>params<span style="color: #990000">[:</span>id<span style="color: #990000">])</span>
1102 send_data<span style="color: #990000">(</span><span style="color: #FF0000">"#{RAILS_ROOT}/files/clients/#{client.id}.pdf"</span><span style="color: #990000">,</span> <span style="color: #990000">:</span>filename <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">"#{client.name}.pdf"</span><span style="color: #990000">,</span> <span style="color: #990000">:</span>type <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">"application/pdf"</span><span style="color: #990000">)</span>
1103 <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
1104
1105 <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
1106 </tt></pre></div></div>
1107 <div class="para"><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>
1108 <div class="admonitionblock">
1109 <table><tr>
1110 <td class="icon">
1111 <img src="./images/icons/warning.png" alt="Warning" />
1112 </td>
1113 <td class="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>
1114 </tr></table>
1115 </div>
1116 <div class="admonitionblock">
1117 <table><tr>
1118 <td class="icon">
1119 <img src="./images/icons/tip.png" alt="Tip" />
1120 </td>
1121 <td class="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.</td>
1122 </tr></table>
1123 </div>
1124 <h3 id="_restful_downloads">11.2. RESTful Downloads</h3>
1125 <div class="para"><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>
1126 <div class="listingblock">
1127 <div class="content"><!-- Generator: GNU source-highlight 2.9
1128 by Lorenzo Bettini
1129 http://www.lorenzobettini.it
1130 http://www.gnu.org/software/src-highlite -->
1131 <pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> ClientsController <span style="color: #990000">&lt;</span> ApplicationController
1132
1133 <span style="font-style: italic"><span style="color: #9A1900"># The user can request to receive this resource as HTML or PDF.</span></span>
1134 <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> show
1135 <span style="color: #009900">@client</span> <span style="color: #990000">=</span> Client<span style="color: #990000">.</span>find<span style="color: #990000">(</span>params<span style="color: #990000">[:</span>id<span style="color: #990000">])</span>
1136
1137 respond_to <span style="font-weight: bold"><span style="color: #0000FF">do</span></span> <span style="color: #990000">|</span>format<span style="color: #990000">|</span>
1138 format<span style="color: #990000">.</span>html
1139 format<span style="color: #990000">.</span>pdf<span style="color: #FF0000">{</span> render <span style="color: #990000">:</span>pdf <span style="color: #990000">=&gt;</span> generate_pdf<span style="color: #990000">(</span><span style="color: #009900">@client</span><span style="color: #990000">)</span> <span style="color: #FF0000">}</span>
1140 <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
1141 <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
1142
1143 <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
1144 </tt></pre></div></div>
1145 <div class="para"><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>
1146 <div class="listingblock">
1147 <div class="content"><!-- Generator: GNU source-highlight 2.9
1148 by Lorenzo Bettini
1149 http://www.lorenzobettini.it
1150 http://www.gnu.org/software/src-highlite -->
1151 <pre><tt>Mime<span style="color: #990000">::</span>Type<span style="color: #990000">.</span>register <span style="color: #FF0000">"application/pdf"</span><span style="color: #990000">,</span> <span style="color: #990000">:</span>pdf
1152 </tt></pre></div></div>
1153 <div class="admonitionblock">
1154 <table><tr>
1155 <td class="icon">
1156 <img src="./images/icons/note.png" alt="Note" />
1157 </td>
1158 <td class="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>
1159 </tr></table>
1160 </div>
1161 <div class="para"><p>Now the user can request to get a PDF version of a client just by adding ".pdf" to the URL:</p></div>
1162 <div class="listingblock">
1163 <div class="content">
1164 <pre><tt>GET /clients/1.pdf</tt></pre>
1165 </div></div>
1166 </div>
1167 <h2 id="_parameter_filtering">12. Parameter Filtering</h2>
1168 <div class="sectionbody">
1169 <div class="para"><p>Rails keeps a log file for each environment (development, test and production) in the "log" 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>
1170 <div class="listingblock">
1171 <div class="content"><!-- Generator: GNU source-highlight 2.9
1172 by Lorenzo Bettini
1173 http://www.lorenzobettini.it
1174 http://www.gnu.org/software/src-highlite -->
1175 <pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> ApplicationController <span style="color: #990000">&lt;</span> ActionController<span style="color: #990000">::</span>Base
1176
1177 filter_parameter_logging <span style="color: #990000">:</span>password
1178
1179 <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
1180 </tt></pre></div></div>
1181 <div class="para"><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 return and replaces those for which the block returns true.</p></div>
1182 </div>
1183 <h2 id="_rescue">13. Rescue</h2>
1184 <div class="sectionbody">
1185 <div class="para"><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>
1186 <h3 id="_the_default_500_and_404_templates">13.1. The Default 500 and 404 Templates</h3>
1187 <div class="para"><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>
1188 <h3 id="_tt_rescue_from_tt">13.2. <tt>rescue_from</tt></h3>
1189 <div class="para"><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>
1190 <div class="para"><p>Here's how you can use <tt>rescue_from</tt> to intercept all ActiveRecord::RecordNotFound errors and do something with them.</p></div>
1191 <div class="listingblock">
1192 <div class="content"><!-- Generator: GNU source-highlight 2.9
1193 by Lorenzo Bettini
1194 http://www.lorenzobettini.it
1195 http://www.gnu.org/software/src-highlite -->
1196 <pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> ApplicationController <span style="color: #990000">&lt;</span> ActionController<span style="color: #990000">::</span>Base
1197
1198 rescue_from ActiveRecord<span style="color: #990000">::</span>RecordNotFound<span style="color: #990000">,</span> <span style="color: #990000">:</span>with <span style="color: #990000">=&gt;</span> <span style="color: #990000">:</span>record_not_found
1199
1200 private
1201
1202 <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> record_not_found
1203 render <span style="color: #990000">:</span>text <span style="color: #990000">=&gt;</span> <span style="color: #FF0000">"404 Not Found"</span><span style="color: #990000">,</span> <span style="color: #990000">:</span>status <span style="color: #990000">=&gt;</span> <span style="color: #993399">404</span>
1204 <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
1205
1206 <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
1207 </tt></pre></div></div>
1208 <div class="para"><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>
1209 <div class="listingblock">
1210 <div class="content"><!-- Generator: GNU source-highlight 2.9
1211 by Lorenzo Bettini
1212 http://www.lorenzobettini.it
1213 http://www.gnu.org/software/src-highlite -->
1214 <pre><tt><span style="font-weight: bold"><span style="color: #0000FF">class</span></span> ApplicationController <span style="color: #990000">&lt;</span> ActionController<span style="color: #990000">::</span>Base
1215
1216 rescue_from User<span style="color: #990000">::</span>NotAuthorized<span style="color: #990000">,</span> <span style="color: #990000">:</span>with <span style="color: #990000">=&gt;</span> <span style="color: #990000">:</span>user_not_authorized
1217
1218 private
1219
1220 <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> user_not_authorized
1221 flash<span style="color: #990000">[:</span>error<span style="color: #990000">]</span> <span style="color: #990000">=</span> <span style="color: #FF0000">"You don't have access to this section."</span>
1222 redirect_to <span style="color: #990000">:</span>back
1223 <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
1224
1225 <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
1226
1227 <span style="font-weight: bold"><span style="color: #0000FF">class</span></span> ClientsController <span style="color: #990000">&lt;</span> ApplicationController
1228
1229 <span style="font-style: italic"><span style="color: #9A1900"># Check that the user has the right authorization to access clients.</span></span>
1230 before_filter <span style="color: #990000">:</span>check_authorization
1231
1232 <span style="font-style: italic"><span style="color: #9A1900"># Note how the actions don't have to worry about all the auth stuff.</span></span>
1233 <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> edit
1234 <span style="color: #009900">@client</span> <span style="color: #990000">=</span> Client<span style="color: #990000">.</span>find<span style="color: #990000">(</span>params<span style="color: #990000">[:</span>id<span style="color: #990000">])</span>
1235 <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
1236
1237 private
1238
1239 <span style="font-style: italic"><span style="color: #9A1900"># If the user is not authorized, just throw the exception.</span></span>
1240 <span style="font-weight: bold"><span style="color: #0000FF">def</span></span> check_authorization
1241 <span style="font-weight: bold"><span style="color: #0000FF">raise</span></span> User<span style="color: #990000">::</span>NotAuthorized <span style="font-weight: bold"><span style="color: #0000FF">unless</span></span> current_user<span style="color: #990000">.</span>admin?
1242 <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
1243
1244 <span style="font-weight: bold"><span style="color: #0000FF">end</span></span>
1245 </tt></pre></div></div>
1246 <div class="admonitionblock">
1247 <table><tr>
1248 <td class="icon">
1249 <img src="./images/icons/note.png" alt="Note" />
1250 </td>
1251 <td class="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 <a href="http://m.onkey.org/2008/7/20/rescue-from-dispatching">article</a> on the subject for more information.</td>
1252 </tr></table>
1253 </div>
1254 </div>
1255 <h2 id="_changelog">14. Changelog</h2>
1256 <div class="sectionbody">
1257 <div class="para"><p><a href="http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/17">Lighthouse ticket</a></p></div>
1258 <div class="ilist"><ul>
1259 <li>
1260 <p>
1261 November 4, 2008: First release version by Tore Darrell
1262 </p>
1263 </li>
1264 </ul></div>
1265 </div>
1266
1267 </div>
1268 </div>
1269 </body>
1270 </html>