railties 3.0.10 → 3.0.11
Sign up to get free protection for your applications and to get access to all the features.
- data/CHANGELOG +12 -1
- data/guides/output/2_2_release_notes.html +565 -0
- data/guides/output/2_3_release_notes.html +713 -0
- data/guides/output/3_0_release_notes.html +652 -0
- data/guides/output/3_1_release_notes.html +670 -0
- data/guides/output/action_controller_overview.html +925 -0
- data/guides/output/action_mailer_basics.html +658 -0
- data/guides/output/action_view_overview.html +1471 -0
- data/guides/output/active_model_basics.html +349 -0
- data/guides/output/active_record_basics.html +364 -0
- data/guides/output/active_record_querying.html +1272 -0
- data/guides/output/active_record_validations_callbacks.html +1292 -0
- data/guides/output/active_resource_basics.html +252 -0
- data/guides/output/active_support_core_extensions.html +3374 -0
- data/guides/output/ajax_on_rails.html +412 -0
- data/guides/output/api_documentation_guidelines.html +317 -0
- data/guides/output/asset_pipeline.html +691 -0
- data/guides/output/association_basics.html +1742 -0
- data/guides/output/caching_with_rails.html +533 -0
- data/guides/output/command_line.html +662 -0
- data/guides/output/configuring.html +811 -0
- data/guides/output/contribute.html +216 -0
- data/guides/output/contributing_to_ruby_on_rails.html +465 -0
- data/guides/output/credits.html +210 -0
- data/guides/output/debugging_rails_applications.html +791 -0
- data/guides/output/engines.html +673 -0
- data/guides/output/form_helpers.html +850 -0
- data/guides/output/generators.html +725 -0
- data/guides/output/getting_started.html +1980 -0
- data/guides/output/i18n.html +1054 -0
- data/guides/output/images/belongs_to.png +0 -0
- data/guides/output/images/book_icon.gif +0 -0
- data/guides/output/images/bullet.gif +0 -0
- data/guides/output/images/challenge.png +0 -0
- data/guides/output/images/chapters_icon.gif +0 -0
- data/guides/output/images/check_bullet.gif +0 -0
- data/guides/output/images/credits_pic_blank.gif +0 -0
- data/guides/output/images/csrf.png +0 -0
- data/guides/output/images/customized_error_messages.png +0 -0
- data/guides/output/images/edge_badge.png +0 -0
- data/guides/output/images/error_messages.png +0 -0
- data/guides/output/images/feature_tile.gif +0 -0
- data/guides/output/images/footer_tile.gif +0 -0
- data/guides/output/images/fxn.png +0 -0
- data/guides/output/images/grey_bullet.gif +0 -0
- data/guides/output/images/habtm.png +0 -0
- data/guides/output/images/has_many.png +0 -0
- data/guides/output/images/has_many_through.png +0 -0
- data/guides/output/images/has_one.png +0 -0
- data/guides/output/images/has_one_through.png +0 -0
- data/guides/output/images/header_backdrop.png +0 -0
- data/guides/output/images/header_tile.gif +0 -0
- data/guides/output/images/i18n/demo_html_safe.png +0 -0
- data/guides/output/images/i18n/demo_localized_pirate.png +0 -0
- data/guides/output/images/i18n/demo_translated_en.png +0 -0
- data/guides/output/images/i18n/demo_translated_pirate.png +0 -0
- data/guides/output/images/i18n/demo_translation_missing.png +0 -0
- data/guides/output/images/i18n/demo_untranslated.png +0 -0
- data/guides/output/images/icons/README +5 -0
- data/guides/output/images/icons/callouts/1.png +0 -0
- data/guides/output/images/icons/callouts/10.png +0 -0
- data/guides/output/images/icons/callouts/11.png +0 -0
- data/guides/output/images/icons/callouts/12.png +0 -0
- data/guides/output/images/icons/callouts/13.png +0 -0
- data/guides/output/images/icons/callouts/14.png +0 -0
- data/guides/output/images/icons/callouts/15.png +0 -0
- data/guides/output/images/icons/callouts/2.png +0 -0
- data/guides/output/images/icons/callouts/3.png +0 -0
- data/guides/output/images/icons/callouts/4.png +0 -0
- data/guides/output/images/icons/callouts/5.png +0 -0
- data/guides/output/images/icons/callouts/6.png +0 -0
- data/guides/output/images/icons/callouts/7.png +0 -0
- data/guides/output/images/icons/callouts/8.png +0 -0
- data/guides/output/images/icons/callouts/9.png +0 -0
- data/guides/output/images/icons/caution.png +0 -0
- data/guides/output/images/icons/example.png +0 -0
- data/guides/output/images/icons/home.png +0 -0
- data/guides/output/images/icons/important.png +0 -0
- data/guides/output/images/icons/next.png +0 -0
- data/guides/output/images/icons/note.png +0 -0
- data/guides/output/images/icons/prev.png +0 -0
- data/guides/output/images/icons/tip.png +0 -0
- data/guides/output/images/icons/up.png +0 -0
- data/guides/output/images/icons/warning.png +0 -0
- data/guides/output/images/jaimeiniesta.jpg +0 -0
- data/guides/output/images/nav_arrow.gif +0 -0
- data/guides/output/images/polymorphic.png +0 -0
- data/guides/output/images/posts_index.png +0 -0
- data/guides/output/images/radar.png +0 -0
- data/guides/output/images/rails_guides_logo.gif +0 -0
- data/guides/output/images/rails_logo_remix.gif +0 -0
- data/guides/output/images/rails_welcome.png +0 -0
- data/guides/output/images/session_fixation.png +0 -0
- data/guides/output/images/tab_grey.gif +0 -0
- data/guides/output/images/tab_info.gif +0 -0
- data/guides/output/images/tab_note.gif +0 -0
- data/guides/output/images/tab_red.gif +0 -0
- data/guides/output/images/tab_yellow.gif +0 -0
- data/guides/output/images/tab_yellow.png +0 -0
- data/guides/output/images/validation_error_messages.png +0 -0
- data/guides/output/images/vijaydev.jpg +0 -0
- data/guides/output/index.html +300 -0
- data/guides/output/initialization.html +1087 -0
- data/guides/output/javascripts/guides.js +7 -0
- data/guides/output/javascripts/syntaxhighlighter/shBrushAS3.js +59 -0
- data/guides/output/javascripts/syntaxhighlighter/shBrushAppleScript.js +75 -0
- data/guides/output/javascripts/syntaxhighlighter/shBrushBash.js +59 -0
- data/guides/output/javascripts/syntaxhighlighter/shBrushCSharp.js +65 -0
- data/guides/output/javascripts/syntaxhighlighter/shBrushColdFusion.js +100 -0
- data/guides/output/javascripts/syntaxhighlighter/shBrushCpp.js +97 -0
- data/guides/output/javascripts/syntaxhighlighter/shBrushCss.js +91 -0
- data/guides/output/javascripts/syntaxhighlighter/shBrushDelphi.js +55 -0
- data/guides/output/javascripts/syntaxhighlighter/shBrushDiff.js +41 -0
- data/guides/output/javascripts/syntaxhighlighter/shBrushErlang.js +52 -0
- data/guides/output/javascripts/syntaxhighlighter/shBrushGroovy.js +67 -0
- data/guides/output/javascripts/syntaxhighlighter/shBrushJScript.js +52 -0
- data/guides/output/javascripts/syntaxhighlighter/shBrushJava.js +57 -0
- data/guides/output/javascripts/syntaxhighlighter/shBrushJavaFX.js +58 -0
- data/guides/output/javascripts/syntaxhighlighter/shBrushPerl.js +72 -0
- data/guides/output/javascripts/syntaxhighlighter/shBrushPhp.js +88 -0
- data/guides/output/javascripts/syntaxhighlighter/shBrushPlain.js +33 -0
- data/guides/output/javascripts/syntaxhighlighter/shBrushPowerShell.js +74 -0
- data/guides/output/javascripts/syntaxhighlighter/shBrushPython.js +64 -0
- data/guides/output/javascripts/syntaxhighlighter/shBrushRuby.js +55 -0
- data/guides/output/javascripts/syntaxhighlighter/shBrushSass.js +94 -0
- data/guides/output/javascripts/syntaxhighlighter/shBrushScala.js +51 -0
- data/guides/output/javascripts/syntaxhighlighter/shBrushSql.js +66 -0
- data/guides/output/javascripts/syntaxhighlighter/shBrushVb.js +56 -0
- data/guides/output/javascripts/syntaxhighlighter/shBrushXml.js +69 -0
- data/guides/output/javascripts/syntaxhighlighter/shCore.js +17 -0
- data/guides/output/layout.html +312 -0
- data/guides/output/layouts_and_rendering.html +1257 -0
- data/guides/output/migrations.html +751 -0
- data/guides/output/nested_model_forms.html +350 -0
- data/guides/output/performance_testing.html +858 -0
- data/guides/output/plugins.html +590 -0
- data/guides/output/rails_application_templates.html +368 -0
- data/guides/output/rails_on_rack.html +408 -0
- data/guides/output/routing.html +1246 -0
- data/guides/output/ruby_on_rails_guides_guidelines.html +218 -0
- data/guides/output/security.html +968 -0
- data/guides/output/stylesheets/fixes.css +16 -0
- data/guides/output/stylesheets/main.css +445 -0
- data/guides/output/stylesheets/print.css +52 -0
- data/guides/output/stylesheets/reset.css +43 -0
- data/guides/output/stylesheets/style.css +13 -0
- data/guides/output/stylesheets/syntaxhighlighter/shCore.css +226 -0
- data/guides/output/stylesheets/syntaxhighlighter/shCoreDefault.css +328 -0
- data/guides/output/stylesheets/syntaxhighlighter/shCoreDjango.css +331 -0
- data/guides/output/stylesheets/syntaxhighlighter/shCoreEclipse.css +339 -0
- data/guides/output/stylesheets/syntaxhighlighter/shCoreEmacs.css +324 -0
- data/guides/output/stylesheets/syntaxhighlighter/shCoreFadeToGrey.css +328 -0
- data/guides/output/stylesheets/syntaxhighlighter/shCoreMDUltra.css +324 -0
- data/guides/output/stylesheets/syntaxhighlighter/shCoreMidnight.css +324 -0
- data/guides/output/stylesheets/syntaxhighlighter/shCoreRDark.css +324 -0
- data/guides/output/stylesheets/syntaxhighlighter/shThemeDefault.css +117 -0
- data/guides/output/stylesheets/syntaxhighlighter/shThemeDjango.css +120 -0
- data/guides/output/stylesheets/syntaxhighlighter/shThemeEclipse.css +128 -0
- data/guides/output/stylesheets/syntaxhighlighter/shThemeEmacs.css +113 -0
- data/guides/output/stylesheets/syntaxhighlighter/shThemeFadeToGrey.css +117 -0
- data/guides/output/stylesheets/syntaxhighlighter/shThemeMDUltra.css +113 -0
- data/guides/output/stylesheets/syntaxhighlighter/shThemeMidnight.css +113 -0
- data/guides/output/stylesheets/syntaxhighlighter/shThemeRDark.css +113 -0
- data/guides/output/stylesheets/syntaxhighlighter/shThemeRailsGuides.css +116 -0
- data/guides/output/testing.html +1182 -0
- data/lib/rails/generators/rails/app/app_generator.rb +1 -1
- data/lib/rails/generators/rails/app/templates/public/javascripts/rails.js +86 -75
- data/lib/rails/tasks/documentation.rake +1 -1
- data/lib/rails/version.rb +1 -1
- metadata +457 -293
@@ -0,0 +1,925 @@
|
|
1
|
+
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
|
2
|
+
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
|
3
|
+
|
4
|
+
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
|
5
|
+
<head>
|
6
|
+
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
|
7
|
+
|
8
|
+
<title>Ruby on Rails Guides: Action Controller Overview</title>
|
9
|
+
|
10
|
+
<link rel="stylesheet" type="text/css" href="stylesheets/style.css" />
|
11
|
+
<link rel="stylesheet" type="text/css" href="stylesheets/print.css" media="print" />
|
12
|
+
|
13
|
+
<link rel="stylesheet" type="text/css" href="stylesheets/syntaxhighlighter/shCore.css" />
|
14
|
+
<link rel="stylesheet" type="text/css" href="stylesheets/syntaxhighlighter/shThemeRailsGuides.css" />
|
15
|
+
|
16
|
+
<link rel="stylesheet" type="text/css" href="stylesheets/fixes.css" />
|
17
|
+
</head>
|
18
|
+
<body class="guide">
|
19
|
+
<div id="topNav">
|
20
|
+
<div class="wrapper">
|
21
|
+
<strong>More at <a href="http://rubyonrails.org/">rubyonrails.org:</a> </strong>
|
22
|
+
<a href="http://rubyonrails.org/">Overview</a> |
|
23
|
+
<a href="http://rubyonrails.org/download">Download</a> |
|
24
|
+
<a href="http://rubyonrails.org/deploy">Deploy</a> |
|
25
|
+
<a href="https://github.com/rails/rails">Code</a> |
|
26
|
+
<a href="http://rubyonrails.org/screencasts">Screencasts</a> |
|
27
|
+
<a href="http://rubyonrails.org/documentation">Documentation</a> |
|
28
|
+
<a href="http://rubyonrails.org/ecosystem">Ecosystem</a> |
|
29
|
+
<a href="http://rubyonrails.org/community">Community</a> |
|
30
|
+
<a href="http://weblog.rubyonrails.org/">Blog</a>
|
31
|
+
</div>
|
32
|
+
</div>
|
33
|
+
<div id="header">
|
34
|
+
<div class="wrapper clearfix">
|
35
|
+
<h1><a href="index.html" title="Return to home page">Guides.rubyonrails.org</a></h1>
|
36
|
+
<p class="hide"><a href="#mainCol">Skip navigation</a>.</p>
|
37
|
+
<ul class="nav">
|
38
|
+
<li><a href="index.html">Home</a></li>
|
39
|
+
<li class="index"><a href="index.html" onclick="guideMenu(); return false;" id="guidesMenu">Guides Index</a>
|
40
|
+
<div id="guides" class="clearfix" style="display: none;">
|
41
|
+
<hr />
|
42
|
+
<dl class="L">
|
43
|
+
<dt>Start Here</dt>
|
44
|
+
<dd><a href="getting_started.html">Getting Started with Rails</a></dd>
|
45
|
+
<dt>Models</dt>
|
46
|
+
<dd><a href="migrations.html">Rails Database Migrations</a></dd>
|
47
|
+
<dd><a href="active_record_validations_callbacks.html">Active Record Validations and Callbacks</a></dd>
|
48
|
+
<dd><a href="association_basics.html">Active Record Associations</a></dd>
|
49
|
+
<dd><a href="active_record_querying.html">Active Record Query Interface</a></dd>
|
50
|
+
<dt>Views</dt>
|
51
|
+
<dd><a href="layouts_and_rendering.html">Layouts and Rendering in Rails</a></dd>
|
52
|
+
<dd><a href="form_helpers.html">Action View Form Helpers</a></dd>
|
53
|
+
<dt>Controllers</dt>
|
54
|
+
<dd><a href="action_controller_overview.html">Action Controller Overview</a></dd>
|
55
|
+
<dd><a href="routing.html">Rails Routing from the Outside In</a></dd>
|
56
|
+
</dl>
|
57
|
+
<dl class="R">
|
58
|
+
<dt>Digging Deeper</dt>
|
59
|
+
<dd><a href="active_support_core_extensions.html">Active Support Core Extensions</a></dd>
|
60
|
+
<dd><a href="i18n.html">Rails Internationalization API</a></dd>
|
61
|
+
<dd><a href="action_mailer_basics.html">Action Mailer Basics</a></dd>
|
62
|
+
<dd><a href="testing.html">Testing Rails Applications</a></dd>
|
63
|
+
<dd><a href="security.html">Securing Rails Applications</a></dd>
|
64
|
+
<dd><a href="debugging_rails_applications.html">Debugging Rails Applications</a></dd>
|
65
|
+
<dd><a href="performance_testing.html">Performance Testing Rails Applications</a></dd>
|
66
|
+
<dd><a href="configuring.html">Configuring Rails Applications</a></dd>
|
67
|
+
<dd><a href="command_line.html">Rails Command Line Tools and Rake Tasks</a></dd>
|
68
|
+
<dd><a href="caching_with_rails.html">Caching with Rails</a></dd>
|
69
|
+
<dd><a href="asset_pipeline.html">Asset Pipeline</a></dd>
|
70
|
+
|
71
|
+
<dt>Extending Rails</dt>
|
72
|
+
<dd><a href="plugins.html">The Basics of Creating Rails Plugins</a></dd>
|
73
|
+
<dd><a href="rails_on_rack.html">Rails on Rack</a></dd>
|
74
|
+
<dd><a href="generators.html">Creating and Customizing Rails Generators</a></dd>
|
75
|
+
|
76
|
+
<dt>Contributing to Ruby on Rails</dt>
|
77
|
+
<dd><a href="contributing_to_ruby_on_rails.html">Contributing to Ruby on Rails</a></dd>
|
78
|
+
<dd><a href="api_documentation_guidelines.html">API Documentation Guidelines</a></dd>
|
79
|
+
<dd><a href="ruby_on_rails_guides_guidelines.html">Ruby on Rails Guides Guidelines</a></dd>
|
80
|
+
|
81
|
+
<dt>Release Notes</dt>
|
82
|
+
<dd><a href="3_1_release_notes.html">Ruby on Rails 3.1 Release Notes</a></dd>
|
83
|
+
<dd><a href="3_0_release_notes.html">Ruby on Rails 3.0 Release Notes</a></dd>
|
84
|
+
<dd><a href="2_3_release_notes.html">Ruby on Rails 2.3 Release Notes</a></dd>
|
85
|
+
<dd><a href="2_2_release_notes.html">Ruby on Rails 2.2 Release Notes</a></dd>
|
86
|
+
</dl>
|
87
|
+
</div>
|
88
|
+
</li>
|
89
|
+
<li><a href="contributing_to_ruby_on_rails.html">Contribute</a></li>
|
90
|
+
<li><a href="credits.html">Credits</a></li>
|
91
|
+
</ul>
|
92
|
+
</div>
|
93
|
+
</div>
|
94
|
+
<hr class="hide" />
|
95
|
+
|
96
|
+
<div id="feature">
|
97
|
+
<div class="wrapper">
|
98
|
+
<h2>Action Controller Overview</h2>
|
99
|
+
<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>
|
100
|
+
<ul>
|
101
|
+
<li>Follow the flow of a request through a controller</li>
|
102
|
+
<li>Understand why and how to store data in the session or cookies</li>
|
103
|
+
<li>Work with filters to execute code during request processing</li>
|
104
|
+
<li>Use Action Controller’s built-in <span class="caps">HTTP</span> authentication</li>
|
105
|
+
<li>Stream data directly to the user’s browser</li>
|
106
|
+
<li>Filter sensitive parameters so they do not appear in the application’s log</li>
|
107
|
+
<li>Deal with exceptions that may be raised during request processing</li>
|
108
|
+
</ul>
|
109
|
+
|
110
|
+
<div id="subCol">
|
111
|
+
<h3 class="chapter"><img src="images/chapters_icon.gif" alt="" />Chapters</h3>
|
112
|
+
<ol class="chapters">
|
113
|
+
<li><a href="#what-does-a-controller-do">What Does a Controller Do?</a></li><li><a href="#methods-and-actions">Methods and Actions</a></li><li><a href="#parameters">Parameters</a><ul><li><a href="#hash-and-array-parameters">Hash and Array Parameters</a></li> <li><a href="#json-xml-parameters"><span class="caps">JSON</span>/<span class="caps">XML</span> parameters</a></li> <li><a href="#routing-parameters">Routing Parameters</a></li> <li><a href="#default_url_options"><tt>default_url_options</tt></a></li></ul></li><li><a href="#session">Session</a><ul><li><a href="#accessing-the-session">Accessing the Session</a></li> <li><a href="#the-flash">The Flash</a></li></ul></li><li><a href="#cookies">Cookies</a></li><li><a href="#rendering-xml-and-json-data">Rendering xml and json data</a></li><li><a href="#filters">Filters</a><ul><li><a href="#after-filters-and-around-filters">After Filters and Around Filters</a></li> <li><a href="#other-ways-to-use-filters">Other Ways to Use Filters</a></li></ul></li><li><a href="#request-forgery-protection">Request Forgery Protection</a></li><li><a href="#the-request-and-response-objects">The Request and Response Objects</a><ul><li><a href="#the-request-object">The <tt>request</tt> Object</a></li> <li><a href="#the-response-object">The <tt>response</tt> Object</a></li></ul></li><li><a href="#http-authentications"><span class="caps">HTTP</span> Authentications</a><ul><li><a href="#http-basic-authentication"><span class="caps">HTTP</span> Basic Authentication</a></li> <li><a href="#http-digest-authentication"><span class="caps">HTTP</span> Digest Authentication</a></li></ul></li><li><a href="#streaming-and-file-downloads">Streaming and File Downloads</a><ul><li><a href="#sending-files">Sending Files</a></li> <li><a href="#restful-downloads">RESTful Downloads</a></li></ul></li><li><a href="#parameter-filtering">Parameter Filtering</a></li><li><a href="#rescue">Rescue</a><ul><li><a href="#the-default-500-and-404-templates">The Default 500 and 404 Templates</a></li> <li><a href="#rescue_from"><tt>rescue_from</tt></a></li></ul></li><li><a href="#force-https-protocol">Force <span class="caps">HTTPS</span> protocol</a></li></ol></div>
|
114
|
+
</div>
|
115
|
+
</div>
|
116
|
+
|
117
|
+
<div id="container">
|
118
|
+
<div class="wrapper">
|
119
|
+
<div id="mainCol">
|
120
|
+
<h3 id="what-does-a-controller-do">1 What Does a Controller Do?</h3>
|
121
|
+
<p>Action Controller is the C in <span class="caps">MVC</span>. 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 straightforward as possible.</p>
|
122
|
+
<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 <span class="caps">HTML</span> 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>
|
123
|
+
<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>
|
124
|
+
<div class="note"><p>For more details on the routing process, see <a href="routing.html">Rails Routing from the Outside In</a>.</p></div>
|
125
|
+
<h3 id="methods-and-actions">2 Methods and Actions</h3>
|
126
|
+
<p>A controller is a Ruby class which inherits from <tt>ApplicationController</tt> 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 method with the same name as the action.</p>
|
127
|
+
<div class="code_container">
|
128
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
129
|
+
class ClientsController < ApplicationController
|
130
|
+
def new
|
131
|
+
end
|
132
|
+
end
|
133
|
+
</pre>
|
134
|
+
</div>
|
135
|
+
<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 <tt>ClientsController</tt> 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 <tt>Client</tt>:</p>
|
136
|
+
<div class="code_container">
|
137
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
138
|
+
def new
|
139
|
+
@client = Client.new
|
140
|
+
end
|
141
|
+
</pre>
|
142
|
+
</div>
|
143
|
+
<p>The <a href="layouts_and_rendering.html">Layouts & Rendering Guide</a> explains this in more detail.</p>
|
144
|
+
<p><tt>ApplicationController</tt> inherits from <tt>ActionController::Base</tt>, 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 <span class="caps">API</span> documentation or in the source itself.</p>
|
145
|
+
<p>Only public methods are callable as actions. It is a best practice to lower the visibility of methods which are not intended to be actions, like auxiliary methods or filters.</p>
|
146
|
+
<h3 id="parameters">3 Parameters</h3>
|
147
|
+
<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 <span class="caps">URL</span>, called query string parameters. The query string is everything after “?” in the <span class="caps">URL</span>. The second type of parameter is usually referred to as <span class="caps">POST</span> data. This information usually comes from an <span class="caps">HTML</span> form which has been filled in by the user. It’s called <span class="caps">POST</span> data because it can only be sent as part of an <span class="caps">HTTP</span> <span class="caps">POST</span> request. Rails does not make any distinction between query string parameters and <span class="caps">POST</span> parameters, and both are available in the <tt>params</tt> hash in your controller:</p>
|
148
|
+
<div class="code_container">
|
149
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
150
|
+
class ClientsController < ActionController::Base
|
151
|
+
# This action uses query string parameters because it gets run
|
152
|
+
# by an HTTP GET request, but this does not make any difference
|
153
|
+
# to the way in which the parameters are accessed. The URL for
|
154
|
+
# this action would look like this in order to list activated
|
155
|
+
# clients: /clients?status=activated
|
156
|
+
def index
|
157
|
+
if params[:status] == "activated"
|
158
|
+
@clients = Client.activated
|
159
|
+
else
|
160
|
+
@clients = Client.unactivated
|
161
|
+
end
|
162
|
+
end
|
163
|
+
|
164
|
+
# This action uses POST parameters. They are most likely coming
|
165
|
+
# from an HTML form which the user has submitted. The URL for
|
166
|
+
# this RESTful request will be "/clients", and the data will be
|
167
|
+
# sent as part of the request body.
|
168
|
+
def create
|
169
|
+
@client = Client.new(params[:client])
|
170
|
+
if @client.save
|
171
|
+
redirect_to @client
|
172
|
+
else
|
173
|
+
# This line overrides the default rendering behavior, which
|
174
|
+
# would have been to render the "create" view.
|
175
|
+
render :action => "new"
|
176
|
+
end
|
177
|
+
end
|
178
|
+
end
|
179
|
+
</pre>
|
180
|
+
</div>
|
181
|
+
<h4 id="hash-and-array-parameters">3.1 Hash and Array Parameters</h4>
|
182
|
+
<p>The <tt>params</tt> hash is not limited to one-dimensional keys and values. It can contain arrays and (nested) hashes. To send an array of values, append an empty pair of square brackets “[]” to the key name:</p>
|
183
|
+
<pre>
|
184
|
+
GET /clients?ids[]=1&ids[]=2&ids[]=3
|
185
|
+
</pre>
|
186
|
+
<div class="note"><p>The actual <span class="caps">URL</span> in this example will be encoded as “/clients?ids%5b%5d=1&ids%5b%5d=2&ids%5b%5d=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.</p></div>
|
187
|
+
<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>
|
188
|
+
<p>To send a hash you include the key name inside the brackets:</p>
|
189
|
+
<div class="code_container">
|
190
|
+
<pre class="brush: xml; gutter: false; toolbar: false">
|
191
|
+
<form accept-charset="UTF-8" action="/clients" method="post">
|
192
|
+
<input type="text" name="client[name]" value="Acme" />
|
193
|
+
<input type="text" name="client[phone]" value="12345" />
|
194
|
+
<input type="text" name="client[address][postcode]" value="12345" />
|
195
|
+
<input type="text" name="client[address][city]" value="Carrot City" />
|
196
|
+
</form>
|
197
|
+
</pre>
|
198
|
+
</div>
|
199
|
+
<p>When this form is submitted, the value of <tt>params[:client]</tt> will be <tt>{"name" => “Acme”, “phone” => “12345”, “address” => {"postcode" => “12345”, “city” => “Carrot City”}}</tt>. Note the nested hash in <tt>params[:client][:address]</tt>.</p>
|
200
|
+
<p>Note that the <tt>params</tt> hash is actually an instance of <tt>HashWithIndifferentAccess</tt> from Active Support, which acts like a hash that lets you use symbols and strings interchangeably as keys.</p>
|
201
|
+
<h4 id="json-xml-parameters">3.2 <span class="caps">JSON</span>/<span class="caps">XML</span> parameters</h4>
|
202
|
+
<p>If you’re writing a web service application, you might find yourself more comfortable on accepting parameters in <span class="caps">JSON</span> or <span class="caps">XML</span> format. Rails will automatically convert your parameters into <tt>params</tt> hash, which you’ll be able to access like you would normally do with form data.</p>
|
203
|
+
<p>So for example, if you are sending this <span class="caps">JSON</span> parameter:</p>
|
204
|
+
<pre>
|
205
|
+
{ "company": { "name": "acme", "address": "123 Carrot Street" } }
|
206
|
+
</pre>
|
207
|
+
<p>You’ll get <tt>params[:company]</tt> as <tt>{ :name => “acme”, “address” => “123 Carrot Street” }</tt>.</p>
|
208
|
+
<p>Also, if you’ve turned on <tt>config.wrap_parameters</tt> in your initializer or calling <tt>wrap_parameters</tt> in your controller, you can safely omit the root element in the <span class="caps">JSON</span>/<span class="caps">XML</span> parameter. The parameters will be cloned and wrapped in the key according to your controller’s name by default. So the above parameter can be written as:</p>
|
209
|
+
<pre>
|
210
|
+
{ "name": "acme", "address": "123 Carrot Street" }
|
211
|
+
</pre>
|
212
|
+
<p>And assume that you’re sending the data to <tt>CompaniesController</tt>, it would then be wrapped in <tt>:company</tt> key like this:</p>
|
213
|
+
<div class="code_container">
|
214
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
215
|
+
{ :name => "acme", :address => "123 Carrot Street", :company => { :name => "acme", :address => "123 Carrot Street" }}
|
216
|
+
</pre>
|
217
|
+
</div>
|
218
|
+
<p>You can customize the name of the key or specific parameters you want to wrap by consulting the <a href="http://api.rubyonrails.org/classes/ActionController/ParamsWrapper.html"><span class="caps">API</span> documentation</a></p>
|
219
|
+
<h4 id="routing-parameters">3.3 Routing Parameters</h4>
|
220
|
+
<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” <span class="caps">URL</span>:</p>
|
221
|
+
<div class="code_container">
|
222
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
223
|
+
match '/clients/:status' => 'clients#index', :foo => "bar"
|
224
|
+
</pre>
|
225
|
+
</div>
|
226
|
+
<p>In this case, when a user opens the <span class="caps">URL</span> <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>
|
227
|
+
<h4 id="default_url_options">3.4 <tt>default_url_options</tt></h4>
|
228
|
+
<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>
|
229
|
+
<div class="code_container">
|
230
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
231
|
+
class ApplicationController < ActionController::Base
|
232
|
+
# The options parameter is the hash passed in to 'url_for'
|
233
|
+
def default_url_options(options)
|
234
|
+
{:locale => I18n.locale}
|
235
|
+
end
|
236
|
+
end
|
237
|
+
</pre>
|
238
|
+
</div>
|
239
|
+
<p>These options will be used as a starting-point when generating URLs, 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 <tt>ApplicationController</tt> so it would be used for all <span class="caps">URL</span> generation, or you could define it on only one controller for all URLs generated there.</p>
|
240
|
+
<h3 id="session">4 Session</h3>
|
241
|
+
<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>
|
242
|
+
<ul>
|
243
|
+
<li>ActionDispatch::Session::CookieStore – Stores everything on the client.</li>
|
244
|
+
<li>ActiveRecord::SessionStore – Stores the data in a database using Active Record.</li>
|
245
|
+
<li>ActionDispatch::Session::CacheStore – Stores the data in the Rails cache.</li>
|
246
|
+
<li>ActionDispatch::Session::MemCacheStore – Stores the data in a memcached cluster (this is a legacy implementation; consider using CacheStore instead).</li>
|
247
|
+
</ul>
|
248
|
+
<p>All session stores use a cookie to store a unique ID for each session (you must use a cookie, Rails will not allow you to pass the session ID in the <span class="caps">URL</span> as this is less secure).</p>
|
249
|
+
<p>For most stores this ID is used to look up the session data on the server, e.g. in a database table. There is one exception, and that is the default and recommended session store – the CookieStore – which stores all session data in the cookie itself (the ID is still available to you if you need it). This has the advantage of being very lightweight and it requires zero setup in a new application in order to use the session. The cookie 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).</p>
|
250
|
+
<p>The CookieStore can store around 4kB of data — much less than the others — but this is usually enough. Storing large amounts of data in the session 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.</p>
|
251
|
+
<p>If your user sessions don’t store critical data or don’t need to be around for long periods (for instance if you just use the flash for messaging), you can consider using ActionDispatch::Session::CacheStore. This will store sessions using the cache implementation you have configured for your application. The advantage of this is that you can use your existing cache infrastructure for storing sessions without requiring any additional setup or administration. The downside, of course, is that the sessions will be ephemeral and could disappear at any time.</p>
|
252
|
+
<p>Read more about session storage in the <a href="security.html">Security Guide</a>.</p>
|
253
|
+
<p>If you need a different session storage mechanism, you can change it in the <tt>config/initializers/session_store.rb</tt> file:</p>
|
254
|
+
<div class="code_container">
|
255
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
256
|
+
# Use the database for sessions instead of the cookie-based default,
|
257
|
+
# which shouldn't be used to store highly confidential information
|
258
|
+
# (create the session table with "script/rails g session_migration")
|
259
|
+
# YourApp::Application.config.session_store :active_record_store
|
260
|
+
</pre>
|
261
|
+
</div>
|
262
|
+
<p>Rails sets up a session key (the name of the cookie) when signing the session data. These can also be changed in <tt>config/initializers/session_store.rb</tt>:</p>
|
263
|
+
<div class="code_container">
|
264
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
265
|
+
# Be sure to restart your server when you modify this file.
|
266
|
+
|
267
|
+
YourApp::Application.config.session_store :cookie_store, :key => '_your_app_session'
|
268
|
+
</pre>
|
269
|
+
</div>
|
270
|
+
<p>You can also pass a <tt>:domain</tt> key and specify the domain name for the cookie:</p>
|
271
|
+
<div class="code_container">
|
272
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
273
|
+
# Be sure to restart your server when you modify this file.
|
274
|
+
|
275
|
+
YourApp::Application.config.session_store :cookie_store, :key => '_your_app_session', :domain => ".example.com"
|
276
|
+
</pre>
|
277
|
+
</div>
|
278
|
+
<p>Rails sets up (for the CookieStore) a secret key used for signing the session data. This can be changed in <tt>config/initializers/secret_token.rb</tt></p>
|
279
|
+
<div class="code_container">
|
280
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
281
|
+
# Be sure to restart your server when you modify this file.
|
282
|
+
|
283
|
+
# Your secret key for verifying the integrity of signed cookies.
|
284
|
+
# If you change this key, all old signed cookies will become invalid!
|
285
|
+
# Make sure the secret is at least 30 characters and all random,
|
286
|
+
# no regular words or you'll be exposed to dictionary attacks.
|
287
|
+
YourApp::Application.config.secret_token = '49d3f3de9ed86c74b94ad6bd0...'
|
288
|
+
</pre>
|
289
|
+
</div>
|
290
|
+
<div class="note"><p>Changing the secret when using the <tt>CookieStore</tt> will invalidate all existing sessions.</p></div>
|
291
|
+
<h4 id="accessing-the-session">4.1 Accessing the Session</h4>
|
292
|
+
<p>In your controller you can access the session through the <tt>session</tt> instance method.</p>
|
293
|
+
<div class="note"><p>Sessions are lazily loaded. If you don’t access sessions in your action’s code, they will not be loaded. Hence you will never need to disable sessions, just not accessing them will do the job.</p></div>
|
294
|
+
<p>Session values are stored using key/value pairs like a hash:</p>
|
295
|
+
<div class="code_container">
|
296
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
297
|
+
class ApplicationController < ActionController::Base
|
298
|
+
|
299
|
+
private
|
300
|
+
|
301
|
+
# Finds the User with the ID stored in the session with the key
|
302
|
+
# :current_user_id This is a common way to handle user login in
|
303
|
+
# a Rails application; logging in sets the session value and
|
304
|
+
# logging out removes it.
|
305
|
+
def current_user
|
306
|
+
@_current_user ||= session[:current_user_id] &&
|
307
|
+
User.find_by_id(session[:current_user_id])
|
308
|
+
end
|
309
|
+
end
|
310
|
+
</pre>
|
311
|
+
</div>
|
312
|
+
<p>To store something in the session, just assign it to the key like a hash:</p>
|
313
|
+
<div class="code_container">
|
314
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
315
|
+
class LoginsController < ApplicationController
|
316
|
+
# "Create" a login, aka "log the user in"
|
317
|
+
def create
|
318
|
+
if user = User.authenticate(params[:username], params[:password])
|
319
|
+
# Save the user ID in the session so it can be used in
|
320
|
+
# subsequent requests
|
321
|
+
session[:current_user_id] = user.id
|
322
|
+
redirect_to root_url
|
323
|
+
end
|
324
|
+
end
|
325
|
+
end
|
326
|
+
</pre>
|
327
|
+
</div>
|
328
|
+
<p>To remove something from the session, assign that key to be <tt>nil</tt>:</p>
|
329
|
+
<div class="code_container">
|
330
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
331
|
+
class LoginsController < ApplicationController
|
332
|
+
# "Delete" a login, aka "log the user out"
|
333
|
+
def destroy
|
334
|
+
# Remove the user id from the session
|
335
|
+
@_current_user = session[:current_user_id] = nil
|
336
|
+
redirect_to root_url
|
337
|
+
end
|
338
|
+
end
|
339
|
+
</pre>
|
340
|
+
</div>
|
341
|
+
<p>To reset the entire session, use <tt>reset_session</tt>.</p>
|
342
|
+
<h4 id="the-flash">4.2 The Flash</h4>
|
343
|
+
<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>
|
344
|
+
<div class="code_container">
|
345
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
346
|
+
class LoginsController < ApplicationController
|
347
|
+
def destroy
|
348
|
+
session[:current_user_id] = nil
|
349
|
+
flash[:notice] = "You have successfully logged out"
|
350
|
+
redirect_to root_url
|
351
|
+
end
|
352
|
+
end
|
353
|
+
</pre>
|
354
|
+
</div>
|
355
|
+
<p>Note it is also possible to assign a flash message as part of the redirection.</p>
|
356
|
+
<div class="code_container">
|
357
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
358
|
+
redirect_to root_url, :notice => "You have successfully logged out"
|
359
|
+
</pre>
|
360
|
+
</div>
|
361
|
+
<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>
|
362
|
+
<div class="code_container">
|
363
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
364
|
+
<html>
|
365
|
+
<!-- <head/> -->
|
366
|
+
<body>
|
367
|
+
<% if flash[:notice] %>
|
368
|
+
<p class="notice"><%= flash[:notice] %></p>
|
369
|
+
<% end %>
|
370
|
+
<% if flash[:error] %>
|
371
|
+
<p class="error"><%= flash[:error] %></p>
|
372
|
+
<% end %>
|
373
|
+
<!-- more content -->
|
374
|
+
</body>
|
375
|
+
</html>
|
376
|
+
</pre>
|
377
|
+
</div>
|
378
|
+
<p>This way, if an action sets an error or a notice message, the layout will display it automatically.</p>
|
379
|
+
<p>If you want a flash value to be carried over to another request, use the <tt>keep</tt> method:</p>
|
380
|
+
<div class="code_container">
|
381
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
382
|
+
class MainController < ApplicationController
|
383
|
+
# Let's say this action corresponds to root_url, but you want
|
384
|
+
# all requests here to be redirected to UsersController#index.
|
385
|
+
# If an action sets the flash and redirects here, the values
|
386
|
+
# would normally be lost when another redirect happens, but you
|
387
|
+
# can use 'keep' to make it persist for another request.
|
388
|
+
def index
|
389
|
+
# Will persist all flash values.
|
390
|
+
flash.keep
|
391
|
+
|
392
|
+
# You can also use a key to keep only some kind of value.
|
393
|
+
# flash.keep(:notice)
|
394
|
+
redirect_to users_url
|
395
|
+
end
|
396
|
+
end
|
397
|
+
</pre>
|
398
|
+
</div>
|
399
|
+
<h5 id="flash-now">4.2.1 <tt>flash.now</tt></h5>
|
400
|
+
<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>
|
401
|
+
<div class="code_container">
|
402
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
403
|
+
class ClientsController < ApplicationController
|
404
|
+
def create
|
405
|
+
@client = Client.new(params[:client])
|
406
|
+
if @client.save
|
407
|
+
# ...
|
408
|
+
else
|
409
|
+
flash.now[:error] = "Could not save client"
|
410
|
+
render :action => "new"
|
411
|
+
end
|
412
|
+
end
|
413
|
+
end
|
414
|
+
</pre>
|
415
|
+
</div>
|
416
|
+
<h3 id="cookies">5 Cookies</h3>
|
417
|
+
<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>
|
418
|
+
<div class="code_container">
|
419
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
420
|
+
class CommentsController < ApplicationController
|
421
|
+
def new
|
422
|
+
# Auto-fill the commenter's name if it has been stored in a cookie
|
423
|
+
@comment = Comment.new(:name => cookies[:commenter_name])
|
424
|
+
end
|
425
|
+
|
426
|
+
def create
|
427
|
+
@comment = Comment.new(params[:comment])
|
428
|
+
if @comment.save
|
429
|
+
flash[:notice] = "Thanks for your comment!"
|
430
|
+
if params[:remember_name]
|
431
|
+
# Remember the commenter's name.
|
432
|
+
cookies[:commenter_name] = @comment.name
|
433
|
+
else
|
434
|
+
# Delete cookie for the commenter's name cookie, if any.
|
435
|
+
cookies.delete(:commenter_name)
|
436
|
+
end
|
437
|
+
redirect_to @comment.article
|
438
|
+
else
|
439
|
+
render :action => "new"
|
440
|
+
end
|
441
|
+
end
|
442
|
+
end
|
443
|
+
</pre>
|
444
|
+
</div>
|
445
|
+
<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>
|
446
|
+
<h3 id="rendering-xml-and-json-data">6 Rendering xml and json data</h3>
|
447
|
+
<p>ActionController makes it extremely easy to render <tt>xml</tt> or <tt>json</tt> data. If you generate a controller using scaffold then your controller would look something like this.</p>
|
448
|
+
<div class="code_container">
|
449
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
450
|
+
class UsersController < ApplicationController
|
451
|
+
def index
|
452
|
+
@users = User.all
|
453
|
+
respond_to do |format|
|
454
|
+
format.html # index.html.erb
|
455
|
+
format.xml { render :xml => @users}
|
456
|
+
format.json { render :json => @users}
|
457
|
+
end
|
458
|
+
end
|
459
|
+
end
|
460
|
+
</pre>
|
461
|
+
</div>
|
462
|
+
<p>Notice that in the above case code is <tt>render :xml => @users</tt> and not <tt>render :xml => @users.to_xml</tt>. That is because if the input is not string then rails automatically invokes <tt>to_xml</tt> .</p>
|
463
|
+
<h3 id="filters">7 Filters</h3>
|
464
|
+
<p>Filters are methods that are run before, after or “around” a controller action.</p>
|
465
|
+
<p>Filters are inherited, so if you set a filter on <tt>ApplicationController</tt>, it will be run on every controller in your application.</p>
|
466
|
+
<p>Before filters may halt the request cycle. A common before 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>
|
467
|
+
<div class="code_container">
|
468
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
469
|
+
class ApplicationController < ActionController::Base
|
470
|
+
before_filter :require_login
|
471
|
+
|
472
|
+
private
|
473
|
+
|
474
|
+
def require_login
|
475
|
+
unless logged_in?
|
476
|
+
flash[:error] = "You must be logged in to access this section"
|
477
|
+
redirect_to new_login_url # halts request cycle
|
478
|
+
end
|
479
|
+
end
|
480
|
+
|
481
|
+
# The logged_in? method simply returns true if the user is logged
|
482
|
+
# in and false otherwise. It does this by "booleanizing" the
|
483
|
+
# current_user method we created previously using a double ! operator.
|
484
|
+
# Note that this is not common in Ruby and is discouraged unless you
|
485
|
+
# really mean to convert something into true or false.
|
486
|
+
def logged_in?
|
487
|
+
!!current_user
|
488
|
+
end
|
489
|
+
end
|
490
|
+
</pre>
|
491
|
+
</div>
|
492
|
+
<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 renders or redirects, the action will not run. If there are additional filters scheduled to run after that filter they are also cancelled.</p>
|
493
|
+
<p>In this example the filter is added to <tt>ApplicationController</tt> and thus all controllers in the application inherit it. 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>
|
494
|
+
<div class="code_container">
|
495
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
496
|
+
class LoginsController < ApplicationController
|
497
|
+
skip_before_filter :require_login, :only => [:new, :create]
|
498
|
+
end
|
499
|
+
</pre>
|
500
|
+
</div>
|
501
|
+
<p>Now, the <tt>LoginsController</tt>’s <tt>new</tt> and <tt>create</tt> actions will work as before without requiring the user to be logged in. The <tt>:only</tt> option is used to only skip this filter for these actions, and there is also an <tt>:except</tt> option which works the other way. These options can be used when adding filters too, so you can add a filter which only runs for selected actions in the first place.</p>
|
502
|
+
<h4 id="after-filters-and-around-filters">7.1 After Filters and Around Filters</h4>
|
503
|
+
<p>In addition to before filters, you can also run filters after an action has been executed, or both before and after.</p>
|
504
|
+
<p>After filters are similar to before filters, but because the action has already been run they have access to the response data that’s about to be sent to the client. Obviously, after filters cannot stop the action from running.</p>
|
505
|
+
<p>Around filters are responsible for running their associated actions by yielding, similar to how Rack middlewares work.</p>
|
506
|
+
<p>For example, in a website where changes have an approval workflow an administrator could be able to preview them easily, just apply them within a transaction:</p>
|
507
|
+
<div class="code_container">
|
508
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
509
|
+
class ChangesController < ActionController::Base
|
510
|
+
around_filter :wrap_in_transaction, :only => :show
|
511
|
+
|
512
|
+
private
|
513
|
+
|
514
|
+
def wrap_in_transaction
|
515
|
+
ActiveRecord::Base.transaction do
|
516
|
+
begin
|
517
|
+
yield
|
518
|
+
ensure
|
519
|
+
raise ActiveRecord::Rollback
|
520
|
+
end
|
521
|
+
end
|
522
|
+
end
|
523
|
+
end
|
524
|
+
</pre>
|
525
|
+
</div>
|
526
|
+
<p>Note that an around filter wraps also rendering. In particular, if in the example above the view itself reads from the database via a scope or whatever, it will do so within the transaction and thus present the data to preview.</p>
|
527
|
+
<p>They can choose not to yield and build the response themselves, in which case the action is not run.</p>
|
528
|
+
<h4 id="other-ways-to-use-filters">7.2 Other Ways to Use Filters</h4>
|
529
|
+
<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>
|
530
|
+
<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>
|
531
|
+
<div class="code_container">
|
532
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
533
|
+
class ApplicationController < ActionController::Base
|
534
|
+
before_filter do |controller|
|
535
|
+
redirect_to new_login_url unless controller.send(:logged_in?)
|
536
|
+
end
|
537
|
+
end
|
538
|
+
</pre>
|
539
|
+
</div>
|
540
|
+
<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>
|
541
|
+
<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 and 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>
|
542
|
+
<div class="code_container">
|
543
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
544
|
+
class ApplicationController < ActionController::Base
|
545
|
+
before_filter LoginFilter
|
546
|
+
end
|
547
|
+
|
548
|
+
class LoginFilter
|
549
|
+
def self.filter(controller)
|
550
|
+
unless controller.send(:logged_in?)
|
551
|
+
controller.flash[:error] = "You must be logged in"
|
552
|
+
controller.redirect_to controller.new_login_url
|
553
|
+
end
|
554
|
+
end
|
555
|
+
end
|
556
|
+
</pre>
|
557
|
+
</div>
|
558
|
+
<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>
|
559
|
+
<h3 id="request-forgery-protection">8 Request Forgery Protection</h3>
|
560
|
+
<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.</p>
|
561
|
+
<p>The first step to avoid this is to make sure all “destructive” actions (create, update and destroy) can only be accessed with non-<span class="caps">GET</span> requests. If you’re following RESTful conventions you’re already doing this. However, a malicious site can still send a non-<span class="caps">GET</span> 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.</p>
|
562
|
+
<p>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>
|
563
|
+
<p>If you generate a form like this:</p>
|
564
|
+
<div class="code_container">
|
565
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
566
|
+
<%= form_for @user do |f| %>
|
567
|
+
<%= f.text_field :username %>
|
568
|
+
<%= f.text_field :password %>
|
569
|
+
<% end %>
|
570
|
+
</pre>
|
571
|
+
</div>
|
572
|
+
<p>You will see how the token gets added as a hidden field:</p>
|
573
|
+
<div class="code_container">
|
574
|
+
<pre class="brush: xml; gutter: false; toolbar: false">
|
575
|
+
<form accept-charset="UTF-8" action="/users/1" method="post">
|
576
|
+
<input type="hidden"
|
577
|
+
value="67250ab105eb5ad10851c00a5621854a23af5489"
|
578
|
+
name="authenticity_token"/>
|
579
|
+
<!-- fields -->
|
580
|
+
</form>
|
581
|
+
</pre>
|
582
|
+
</div>
|
583
|
+
<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>
|
584
|
+
<p>The <tt>form_authenticity_token</tt> generates a valid authentication token. That’s useful in places where Rails does not add it automatically, like in custom Ajax calls.</p>
|
585
|
+
<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>
|
586
|
+
<h3 id="the-request-and-response-objects">9 The Request and Response Objects</h3>
|
587
|
+
<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 <tt>AbstractRequest</tt> and the <tt>response</tt> method returns a response object representing what is going to be sent back to the client.</p>
|
588
|
+
<h4 id="the-request-object">9.1 The <tt>request</tt> Object</h4>
|
589
|
+
<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/ActionDispatch/Request.html"><span class="caps">API</span> documentation</a>. Among the properties that you can access on this object are:</p>
|
590
|
+
<table>
|
591
|
+
<tr>
|
592
|
+
<th>Property of <tt>request</tt></th>
|
593
|
+
<th>Purpose</th>
|
594
|
+
</tr>
|
595
|
+
<tr>
|
596
|
+
<td>host</td>
|
597
|
+
<td>The hostname used for this request.</td>
|
598
|
+
</tr>
|
599
|
+
<tr>
|
600
|
+
<td>domain(n=2)</td>
|
601
|
+
<td>The hostname’s first <tt>n</tt> segments, starting from the right (the <span class="caps">TLD</span>).</td>
|
602
|
+
</tr>
|
603
|
+
<tr>
|
604
|
+
<td>format</td>
|
605
|
+
<td>The content type requested by the client.</td>
|
606
|
+
</tr>
|
607
|
+
<tr>
|
608
|
+
<td>method</td>
|
609
|
+
<td>The <span class="caps">HTTP</span> method used for the request.</td>
|
610
|
+
</tr>
|
611
|
+
<tr>
|
612
|
+
<td>get?, post?, put?, delete?, head?</td>
|
613
|
+
<td>Returns true if the <span class="caps">HTTP</span> method is <span class="caps">GET</span>/<span class="caps">POST</span>/<span class="caps">PUT</span>/<span class="caps">DELETE</span>/<span class="caps">HEAD</span>.</td>
|
614
|
+
</tr>
|
615
|
+
<tr>
|
616
|
+
<td>headers</td>
|
617
|
+
<td>Returns a hash containing the headers associated with the request.</td>
|
618
|
+
</tr>
|
619
|
+
<tr>
|
620
|
+
<td>port</td>
|
621
|
+
<td>The port number (integer) used for the request.</td>
|
622
|
+
</tr>
|
623
|
+
<tr>
|
624
|
+
<td>protocol</td>
|
625
|
+
<td>Returns a string containing the protocol used plus “://”, for example “http://”.</td>
|
626
|
+
</tr>
|
627
|
+
<tr>
|
628
|
+
<td>query_string</td>
|
629
|
+
<td>The query string part of the <span class="caps">URL</span>, i.e., everything after “?”.</td>
|
630
|
+
</tr>
|
631
|
+
<tr>
|
632
|
+
<td>remote_ip</td>
|
633
|
+
<td>The IP address of the client.</td>
|
634
|
+
</tr>
|
635
|
+
<tr>
|
636
|
+
<td>url</td>
|
637
|
+
<td>The entire <span class="caps">URL</span> used for the request.</td>
|
638
|
+
</tr>
|
639
|
+
</table>
|
640
|
+
<h5 id="path_parameters-query_parameters-and-request_parameters">9.1.1 <tt>path_parameters</tt>, <tt>query_parameters</tt>, and <tt>request_parameters</tt></h5>
|
641
|
+
<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>
|
642
|
+
<h4 id="the-response-object">9.2 The <tt>response</tt> Object</h4>
|
643
|
+
<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>
|
644
|
+
<table>
|
645
|
+
<tr>
|
646
|
+
<th>Property of <tt>response</tt></th>
|
647
|
+
<th>Purpose</th>
|
648
|
+
</tr>
|
649
|
+
<tr>
|
650
|
+
<td>body</td>
|
651
|
+
<td>This is the string of data being sent back to the client. This is most often <span class="caps">HTML</span>.</td>
|
652
|
+
</tr>
|
653
|
+
<tr>
|
654
|
+
<td>status</td>
|
655
|
+
<td>The <span class="caps">HTTP</span> status code for the response, like 200 for a successful request or 404 for file not found.</td>
|
656
|
+
</tr>
|
657
|
+
<tr>
|
658
|
+
<td>location</td>
|
659
|
+
<td>The <span class="caps">URL</span> the client is being redirected to, if any.</td>
|
660
|
+
</tr>
|
661
|
+
<tr>
|
662
|
+
<td>content_type</td>
|
663
|
+
<td>The content type of the response.</td>
|
664
|
+
</tr>
|
665
|
+
<tr>
|
666
|
+
<td>charset</td>
|
667
|
+
<td>The character set being used for the response. Default is “utf-8”.</td>
|
668
|
+
</tr>
|
669
|
+
<tr>
|
670
|
+
<td>headers</td>
|
671
|
+
<td>Headers used for the response.</td>
|
672
|
+
</tr>
|
673
|
+
</table>
|
674
|
+
<h5 id="setting-custom-headers">9.2.1 Setting Custom Headers</h5>
|
675
|
+
<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 automatically. If you want to add or change a header, just assign it to <tt>response.headers</tt> this way:</p>
|
676
|
+
<div class="code_container">
|
677
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
678
|
+
response.headers["Content-Type"] = "application/pdf"
|
679
|
+
</pre>
|
680
|
+
</div>
|
681
|
+
<h3 id="http-authentications">10 <span class="caps">HTTP</span> Authentications</h3>
|
682
|
+
<p>Rails comes with two built-in <span class="caps">HTTP</span> authentication mechanisms:</p>
|
683
|
+
<ul>
|
684
|
+
<li>Basic Authentication</li>
|
685
|
+
<li>Digest Authentication</li>
|
686
|
+
</ul>
|
687
|
+
<h4 id="http-basic-authentication">10.1 <span class="caps">HTTP</span> Basic Authentication</h4>
|
688
|
+
<p><span class="caps">HTTP</span> basic authentication is an authentication scheme that is supported by the majority of browsers and other <span class="caps">HTTP</span> clients. As an example, consider an administration section which will only be available by entering a username and a password into the browser’s <span class="caps">HTTP</span> basic dialog window. Using the built-in authentication is quite easy and only requires you to use one method, <tt>http_basic_authenticate_with</tt>.</p>
|
689
|
+
<div class="code_container">
|
690
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
691
|
+
class AdminController < ApplicationController
|
692
|
+
http_basic_authenticate_with :name => "humbaba", :password => "5baa61e4"
|
693
|
+
end
|
694
|
+
</pre>
|
695
|
+
</div>
|
696
|
+
<p>With this in place, you can create namespaced controllers that inherit from <tt>AdminController</tt>. The filter will thus be run for all actions in those controllers, protecting them with <span class="caps">HTTP</span> basic authentication.</p>
|
697
|
+
<h4 id="http-digest-authentication">10.2 <span class="caps">HTTP</span> Digest Authentication</h4>
|
698
|
+
<p><span class="caps">HTTP</span> digest authentication is superior to the basic authentication as it does not require the client to send an unencrypted password over the network (though <span class="caps">HTTP</span> basic authentication is safe over <span class="caps">HTTPS</span>). Using digest authentication with Rails is quite easy and only requires using one method, <tt>authenticate_or_request_with_http_digest</tt>.</p>
|
699
|
+
<div class="code_container">
|
700
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
701
|
+
class AdminController < ApplicationController
|
702
|
+
USERS = { "lifo" => "world" }
|
703
|
+
|
704
|
+
before_filter :authenticate
|
705
|
+
|
706
|
+
private
|
707
|
+
|
708
|
+
def authenticate
|
709
|
+
authenticate_or_request_with_http_digest do |username|
|
710
|
+
USERS[username]
|
711
|
+
end
|
712
|
+
end
|
713
|
+
end
|
714
|
+
</pre>
|
715
|
+
</div>
|
716
|
+
<p>As seen in the example above, the <tt>authenticate_or_request_with_http_digest</tt> block takes only one argument – the username. And the block returns the password. Returning <tt>false</tt> or <tt>nil</tt> from the <tt>authenticate_or_request_with_http_digest</tt> will cause authentication failure.</p>
|
717
|
+
<h3 id="streaming-and-file-downloads">11 Streaming and File Downloads</h3>
|
718
|
+
<p>Sometimes you may want to send a file to the user instead of rendering an <span class="caps">HTML</span> page. All controllers in Rails have the <tt>send_data</tt> and the <tt>send_file</tt> methods, which will both stream data to the client. <tt>send_file</tt> is a convenience method that lets you provide the name of a file on the disk and it will stream the contents of that file for you.</p>
|
719
|
+
<p>To stream data to the client, use <tt>send_data</tt>:</p>
|
720
|
+
<div class="code_container">
|
721
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
722
|
+
require "prawn"
|
723
|
+
class ClientsController < ApplicationController
|
724
|
+
# Generates a PDF document with information on the client and
|
725
|
+
# returns it. The user will get the PDF as a file download.
|
726
|
+
def download_pdf
|
727
|
+
client = Client.find(params[:id])
|
728
|
+
send_data generate_pdf(client),
|
729
|
+
:filename => "#{client.name}.pdf",
|
730
|
+
:type => "application/pdf"
|
731
|
+
end
|
732
|
+
|
733
|
+
private
|
734
|
+
|
735
|
+
def generate_pdf(client)
|
736
|
+
Prawn::Document.new do
|
737
|
+
text client.name, :align => :center
|
738
|
+
text "Address: #{client.address}"
|
739
|
+
text "Email: #{client.email}"
|
740
|
+
end.render
|
741
|
+
end
|
742
|
+
end
|
743
|
+
</pre>
|
744
|
+
</div>
|
745
|
+
<p>The <tt>download_pdf</tt> action in the example above will call a private method which actually generates the <span class="caps">PDF</span> 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 <span class="caps">HTML</span> 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>
|
746
|
+
<h4 id="sending-files">11.1 Sending Files</h4>
|
747
|
+
<p>If you want to send a file that already exists on disk, use the <tt>send_file</tt> method.</p>
|
748
|
+
<div class="code_container">
|
749
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
750
|
+
class ClientsController < ApplicationController
|
751
|
+
# Stream a file that has already been generated and stored on disk.
|
752
|
+
def download_pdf
|
753
|
+
client = Client.find(params[:id])
|
754
|
+
send_file("#{Rails.root}/files/clients/#{client.id}.pdf",
|
755
|
+
:filename => "#{client.name}.pdf",
|
756
|
+
:type => "application/pdf")
|
757
|
+
end
|
758
|
+
end
|
759
|
+
</pre>
|
760
|
+
</div>
|
761
|
+
<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>
|
762
|
+
<p>If <tt>:type</tt> is not specified, it will be guessed from the file extension specified in <tt>:filename</tt>. If the content type is not registered for the extension, <tt>application/octet-stream</tt> will be used.</p>
|
763
|
+
<div class="warning"><p>Be careful when using data coming from the client (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.</p></div>
|
764
|
+
<div class="info"><p>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.</p></div>
|
765
|
+
<h4 id="restful-downloads">11.2 RESTful Downloads</h4>
|
766
|
+
<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 <span class="caps">REST</span> terminology, the <span class="caps">PDF</span> 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 <span class="caps">PDF</span> download is a part of the <tt>show</tt> action, without any streaming:</p>
|
767
|
+
<div class="code_container">
|
768
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
769
|
+
class ClientsController < ApplicationController
|
770
|
+
# The user can request to receive this resource as HTML or PDF.
|
771
|
+
def show
|
772
|
+
@client = Client.find(params[:id])
|
773
|
+
|
774
|
+
respond_to do |format|
|
775
|
+
format.html
|
776
|
+
format.pdf { render :pdf => generate_pdf(@client) }
|
777
|
+
end
|
778
|
+
end
|
779
|
+
end
|
780
|
+
</pre>
|
781
|
+
</div>
|
782
|
+
<p>In order for this example to work, you have to add the <span class="caps">PDF</span> <span class="caps">MIME</span> type to Rails. This can be done by adding the following line to the file <tt>config/initializers/mime_types.rb</tt>:</p>
|
783
|
+
<div class="code_container">
|
784
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
785
|
+
Mime::Type.register "application/pdf", :pdf
|
786
|
+
</pre>
|
787
|
+
</div>
|
788
|
+
<div class="note"><p>Configuration files are not reloaded on each request, so you have to restart the server in order for their changes to take effect.</p></div>
|
789
|
+
<p>Now the user can request to get a <span class="caps">PDF</span> version of a client just by adding “.pdf” to the <span class="caps">URL</span>:</p>
|
790
|
+
<div class="code_container">
|
791
|
+
<pre class="brush: plain; gutter: false; toolbar: false">
|
792
|
+
GET /clients/1.pdf
|
793
|
+
</pre>
|
794
|
+
</div>
|
795
|
+
<h3 id="parameter-filtering">12 Parameter Filtering</h3>
|
796
|
+
<p>Rails keeps a log file for each environment in the <tt>log</tt> folder. These are extremely useful when debugging what’s actually going on in your application, but in a live application you may not want every bit of information to be stored in the log file. You can filter certain request parameters from your log files by appending them to <tt>config.filter_parameters</tt> in the application configuration. These parameters will be marked [<span class="caps">FILTERED</span>] in the log.</p>
|
797
|
+
<div class="code_container">
|
798
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
799
|
+
config.filter_parameters << :password
|
800
|
+
</pre>
|
801
|
+
</div>
|
802
|
+
<h3 id="rescue">13 Rescue</h3>
|
803
|
+
<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 <tt>ActiveRecord::RecordNotFound</tt> exception.</p>
|
804
|
+
<p>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>
|
805
|
+
<h4 id="the-default-500-and-404-templates">13.1 The Default 500 and 404 Templates</h4>
|
806
|
+
<p>By default a production application will render either a 404 or a 500 error message. These messages are contained in static <span class="caps">HTML</span> 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 <span class="caps">RHTML</span> or layouts in them, just plain <span class="caps">HTML</span>.</p>
|
807
|
+
<h4 id="rescue_from">13.2 <tt>rescue_from</tt></h4>
|
808
|
+
<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.</p>
|
809
|
+
<p>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 <tt>Proc</tt> object passed to the <tt>:with</tt> option. You can also use a block directly instead of an explicit <tt>Proc</tt> object.</p>
|
810
|
+
<p>Here’s how you can use <tt>rescue_from</tt> to intercept all <tt>ActiveRecord::RecordNotFound</tt> errors and do something with them.</p>
|
811
|
+
<div class="code_container">
|
812
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
813
|
+
class ApplicationController < ActionController::Base
|
814
|
+
rescue_from ActiveRecord::RecordNotFound, :with => :record_not_found
|
815
|
+
|
816
|
+
private
|
817
|
+
|
818
|
+
def record_not_found
|
819
|
+
render :text => "404 Not Found", :status => 404
|
820
|
+
end
|
821
|
+
end
|
822
|
+
</pre>
|
823
|
+
</div>
|
824
|
+
<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>
|
825
|
+
<div class="code_container">
|
826
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
827
|
+
class ApplicationController < ActionController::Base
|
828
|
+
rescue_from User::NotAuthorized, :with => :user_not_authorized
|
829
|
+
|
830
|
+
private
|
831
|
+
|
832
|
+
def user_not_authorized
|
833
|
+
flash[:error] = "You don't have access to this section."
|
834
|
+
redirect_to :back
|
835
|
+
end
|
836
|
+
end
|
837
|
+
|
838
|
+
class ClientsController < ApplicationController
|
839
|
+
# Check that the user has the right authorization to access clients.
|
840
|
+
before_filter :check_authorization
|
841
|
+
|
842
|
+
# Note how the actions don't have to worry about all the auth stuff.
|
843
|
+
def edit
|
844
|
+
@client = Client.find(params[:id])
|
845
|
+
end
|
846
|
+
|
847
|
+
private
|
848
|
+
|
849
|
+
# If the user is not authorized, just throw the exception.
|
850
|
+
def check_authorization
|
851
|
+
raise User::NotAuthorized unless current_user.admin?
|
852
|
+
end
|
853
|
+
end
|
854
|
+
</pre>
|
855
|
+
</div>
|
856
|
+
<div class="note"><p>Certain exceptions are only rescuable from the <tt>ApplicationController</tt> 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.</p></div>
|
857
|
+
<h3 id="force-https-protocol">14 Force <span class="caps">HTTPS</span> protocol</h3>
|
858
|
+
<p>Sometime you might want to force a particular controller to only be accessible via an <span class="caps">HTTPS</span> protocol for security reasons. Since Rails 3.1 you can now use <tt>force_ssl</tt> method in your controller to enforce that:</p>
|
859
|
+
<div class="code_container">
|
860
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
861
|
+
class DinnerController
|
862
|
+
force_ssl
|
863
|
+
end
|
864
|
+
</pre>
|
865
|
+
</div>
|
866
|
+
<p>Just like the filter, you could also passing <tt>:only</tt> and <tt>:except</tt> to enforce the secure connection only to specific actions.</p>
|
867
|
+
<div class="code_container">
|
868
|
+
<pre class="brush: ruby; gutter: false; toolbar: false">
|
869
|
+
class DinnerController
|
870
|
+
force_ssl :only => :cheeseburger
|
871
|
+
# or
|
872
|
+
force_ssl :except => :cheeseburger
|
873
|
+
end
|
874
|
+
</pre>
|
875
|
+
</div>
|
876
|
+
<p>Please note that if you found yourself adding <tt>force_ssl</tt> to many controllers, you may found yourself wanting to force the whole application to use <span class="caps">HTTPS</span> instead. In that case, you can set the <tt>config.force_ssl</tt> in your environment file.</p>
|
877
|
+
|
878
|
+
<h3>Feedback</h3>
|
879
|
+
<p>
|
880
|
+
You're encouraged to help improve the quality of this guide.
|
881
|
+
</p>
|
882
|
+
<p>
|
883
|
+
If you see any typos or factual errors you are confident to
|
884
|
+
patch, please clone <a href="https://github.com/lifo/docrails">docrails</a>
|
885
|
+
and push the change yourself. That branch of Rails has public write access.
|
886
|
+
Commits are still reviewed, but that happens after you've submitted your
|
887
|
+
contribution. <a href="https://github.com/lifo/docrails">docrails</a> is
|
888
|
+
cross-merged with master periodically.
|
889
|
+
</p>
|
890
|
+
<p>
|
891
|
+
You may also find incomplete content, or stuff that is not up to date.
|
892
|
+
Please do add any missing documentation for master. Check the
|
893
|
+
<a href="ruby_on_rails_guides_guidelines.html">Ruby on Rails Guides Guidelines</a>
|
894
|
+
for style and conventions.
|
895
|
+
</p>
|
896
|
+
<p>
|
897
|
+
If for whatever reason you spot something to fix but cannot patch it yourself, please
|
898
|
+
<a href="https://github.com/rails/rails/issues">open an issue</a>.
|
899
|
+
</p>
|
900
|
+
<p>And last but not least, any kind of discussion regarding Ruby on Rails
|
901
|
+
documentation is very welcome in the <a href="http://groups.google.com/group/rubyonrails-docs">rubyonrails-docs mailing list</a>.
|
902
|
+
</p>
|
903
|
+
</div>
|
904
|
+
</div>
|
905
|
+
</div>
|
906
|
+
|
907
|
+
<hr class="hide" />
|
908
|
+
<div id="footer">
|
909
|
+
<div class="wrapper">
|
910
|
+
<p>This work is licensed under a <a href="http://creativecommons.org/licenses/by-sa/3.0/">Creative Commons Attribution-Share Alike 3.0</a> License</p>
|
911
|
+
<p>"Rails", "Ruby on Rails", and the Rails logo are trademarks of David Heinemeier Hansson. All rights reserved.</p>
|
912
|
+
</div>
|
913
|
+
</div>
|
914
|
+
|
915
|
+
<script type="text/javascript" src="javascripts/guides.js"></script>
|
916
|
+
<script type="text/javascript" src="javascripts/syntaxhighlighter/shCore.js"></script>
|
917
|
+
<script type="text/javascript" src="javascripts/syntaxhighlighter/shBrushRuby.js"></script>
|
918
|
+
<script type="text/javascript" src="javascripts/syntaxhighlighter/shBrushXml.js"></script>
|
919
|
+
<script type="text/javascript" src="javascripts/syntaxhighlighter/shBrushSql.js"></script>
|
920
|
+
<script type="text/javascript" src="javascripts/syntaxhighlighter/shBrushPlain.js"></script>
|
921
|
+
<script type="text/javascript">
|
922
|
+
SyntaxHighlighter.all()
|
923
|
+
</script>
|
924
|
+
</body>
|
925
|
+
</html>
|