rails 4.2.6.rc1 → 5.2.8.1

Sign up to get free protection for your applications and to get access to all the features.

Potentially problematic release.


This version of rails might be problematic. Click here for more details.

Files changed (218) hide show
  1. checksums.yaml +5 -5
  2. data/README.md +24 -12
  3. metadata +54 -248
  4. data/guides/CHANGELOG.md +0 -73
  5. data/guides/Rakefile +0 -79
  6. data/guides/assets/images/akshaysurve.jpg +0 -0
  7. data/guides/assets/images/belongs_to.png +0 -0
  8. data/guides/assets/images/book_icon.gif +0 -0
  9. data/guides/assets/images/bullet.gif +0 -0
  10. data/guides/assets/images/chapters_icon.gif +0 -0
  11. data/guides/assets/images/check_bullet.gif +0 -0
  12. data/guides/assets/images/credits_pic_blank.gif +0 -0
  13. data/guides/assets/images/csrf.png +0 -0
  14. data/guides/assets/images/edge_badge.png +0 -0
  15. data/guides/assets/images/favicon.ico +0 -0
  16. data/guides/assets/images/feature_tile.gif +0 -0
  17. data/guides/assets/images/footer_tile.gif +0 -0
  18. data/guides/assets/images/fxn.png +0 -0
  19. data/guides/assets/images/getting_started/article_with_comments.png +0 -0
  20. data/guides/assets/images/getting_started/challenge.png +0 -0
  21. data/guides/assets/images/getting_started/confirm_dialog.png +0 -0
  22. data/guides/assets/images/getting_started/forbidden_attributes_for_new_article.png +0 -0
  23. data/guides/assets/images/getting_started/form_with_errors.png +0 -0
  24. data/guides/assets/images/getting_started/index_action_with_edit_link.png +0 -0
  25. data/guides/assets/images/getting_started/new_article.png +0 -0
  26. data/guides/assets/images/getting_started/rails_welcome.png +0 -0
  27. data/guides/assets/images/getting_started/routing_error_no_controller.png +0 -0
  28. data/guides/assets/images/getting_started/routing_error_no_route_matches.png +0 -0
  29. data/guides/assets/images/getting_started/show_action_for_articles.png +0 -0
  30. data/guides/assets/images/getting_started/template_is_missing_articles_new.png +0 -0
  31. data/guides/assets/images/getting_started/unknown_action_create_for_articles.png +0 -0
  32. data/guides/assets/images/getting_started/unknown_action_new_for_articles.png +0 -0
  33. data/guides/assets/images/grey_bullet.gif +0 -0
  34. data/guides/assets/images/habtm.png +0 -0
  35. data/guides/assets/images/has_many.png +0 -0
  36. data/guides/assets/images/has_many_through.png +0 -0
  37. data/guides/assets/images/has_one.png +0 -0
  38. data/guides/assets/images/has_one_through.png +0 -0
  39. data/guides/assets/images/header_backdrop.png +0 -0
  40. data/guides/assets/images/header_tile.gif +0 -0
  41. data/guides/assets/images/i18n/demo_html_safe.png +0 -0
  42. data/guides/assets/images/i18n/demo_localized_pirate.png +0 -0
  43. data/guides/assets/images/i18n/demo_translated_en.png +0 -0
  44. data/guides/assets/images/i18n/demo_translated_pirate.png +0 -0
  45. data/guides/assets/images/i18n/demo_translation_missing.png +0 -0
  46. data/guides/assets/images/i18n/demo_untranslated.png +0 -0
  47. data/guides/assets/images/icons/README +0 -5
  48. data/guides/assets/images/icons/callouts/1.png +0 -0
  49. data/guides/assets/images/icons/callouts/10.png +0 -0
  50. data/guides/assets/images/icons/callouts/11.png +0 -0
  51. data/guides/assets/images/icons/callouts/12.png +0 -0
  52. data/guides/assets/images/icons/callouts/13.png +0 -0
  53. data/guides/assets/images/icons/callouts/14.png +0 -0
  54. data/guides/assets/images/icons/callouts/15.png +0 -0
  55. data/guides/assets/images/icons/callouts/2.png +0 -0
  56. data/guides/assets/images/icons/callouts/3.png +0 -0
  57. data/guides/assets/images/icons/callouts/4.png +0 -0
  58. data/guides/assets/images/icons/callouts/5.png +0 -0
  59. data/guides/assets/images/icons/callouts/6.png +0 -0
  60. data/guides/assets/images/icons/callouts/7.png +0 -0
  61. data/guides/assets/images/icons/callouts/8.png +0 -0
  62. data/guides/assets/images/icons/callouts/9.png +0 -0
  63. data/guides/assets/images/icons/caution.png +0 -0
  64. data/guides/assets/images/icons/example.png +0 -0
  65. data/guides/assets/images/icons/home.png +0 -0
  66. data/guides/assets/images/icons/important.png +0 -0
  67. data/guides/assets/images/icons/next.png +0 -0
  68. data/guides/assets/images/icons/note.png +0 -0
  69. data/guides/assets/images/icons/prev.png +0 -0
  70. data/guides/assets/images/icons/tip.png +0 -0
  71. data/guides/assets/images/icons/up.png +0 -0
  72. data/guides/assets/images/icons/warning.png +0 -0
  73. data/guides/assets/images/nav_arrow.gif +0 -0
  74. data/guides/assets/images/oscardelben.jpg +0 -0
  75. data/guides/assets/images/polymorphic.png +0 -0
  76. data/guides/assets/images/radar.png +0 -0
  77. data/guides/assets/images/rails4_features.png +0 -0
  78. data/guides/assets/images/rails_guides_kindle_cover.jpg +0 -0
  79. data/guides/assets/images/rails_guides_logo.gif +0 -0
  80. data/guides/assets/images/rails_logo_remix.gif +0 -0
  81. data/guides/assets/images/session_fixation.png +0 -0
  82. data/guides/assets/images/tab_grey.gif +0 -0
  83. data/guides/assets/images/tab_info.gif +0 -0
  84. data/guides/assets/images/tab_note.gif +0 -0
  85. data/guides/assets/images/tab_red.gif +0 -0
  86. data/guides/assets/images/tab_yellow.gif +0 -0
  87. data/guides/assets/images/tab_yellow.png +0 -0
  88. data/guides/assets/images/vijaydev.jpg +0 -0
  89. data/guides/assets/javascripts/guides.js +0 -59
  90. data/guides/assets/javascripts/jquery.min.js +0 -4
  91. data/guides/assets/javascripts/responsive-tables.js +0 -43
  92. data/guides/assets/javascripts/syntaxhighlighter/shBrushAS3.js +0 -59
  93. data/guides/assets/javascripts/syntaxhighlighter/shBrushAppleScript.js +0 -75
  94. data/guides/assets/javascripts/syntaxhighlighter/shBrushBash.js +0 -59
  95. data/guides/assets/javascripts/syntaxhighlighter/shBrushCSharp.js +0 -65
  96. data/guides/assets/javascripts/syntaxhighlighter/shBrushColdFusion.js +0 -100
  97. data/guides/assets/javascripts/syntaxhighlighter/shBrushCpp.js +0 -97
  98. data/guides/assets/javascripts/syntaxhighlighter/shBrushCss.js +0 -91
  99. data/guides/assets/javascripts/syntaxhighlighter/shBrushDelphi.js +0 -55
  100. data/guides/assets/javascripts/syntaxhighlighter/shBrushDiff.js +0 -41
  101. data/guides/assets/javascripts/syntaxhighlighter/shBrushErlang.js +0 -52
  102. data/guides/assets/javascripts/syntaxhighlighter/shBrushGroovy.js +0 -67
  103. data/guides/assets/javascripts/syntaxhighlighter/shBrushJScript.js +0 -52
  104. data/guides/assets/javascripts/syntaxhighlighter/shBrushJava.js +0 -57
  105. data/guides/assets/javascripts/syntaxhighlighter/shBrushJavaFX.js +0 -58
  106. data/guides/assets/javascripts/syntaxhighlighter/shBrushPerl.js +0 -72
  107. data/guides/assets/javascripts/syntaxhighlighter/shBrushPhp.js +0 -88
  108. data/guides/assets/javascripts/syntaxhighlighter/shBrushPlain.js +0 -33
  109. data/guides/assets/javascripts/syntaxhighlighter/shBrushPowerShell.js +0 -74
  110. data/guides/assets/javascripts/syntaxhighlighter/shBrushPython.js +0 -64
  111. data/guides/assets/javascripts/syntaxhighlighter/shBrushRuby.js +0 -55
  112. data/guides/assets/javascripts/syntaxhighlighter/shBrushSass.js +0 -94
  113. data/guides/assets/javascripts/syntaxhighlighter/shBrushScala.js +0 -51
  114. data/guides/assets/javascripts/syntaxhighlighter/shBrushSql.js +0 -66
  115. data/guides/assets/javascripts/syntaxhighlighter/shBrushVb.js +0 -56
  116. data/guides/assets/javascripts/syntaxhighlighter/shBrushXml.js +0 -69
  117. data/guides/assets/javascripts/syntaxhighlighter/shCore.js +0 -17
  118. data/guides/assets/stylesheets/fixes.css +0 -16
  119. data/guides/assets/stylesheets/kindle.css +0 -11
  120. data/guides/assets/stylesheets/main.css +0 -713
  121. data/guides/assets/stylesheets/print.css +0 -52
  122. data/guides/assets/stylesheets/reset.css +0 -43
  123. data/guides/assets/stylesheets/responsive-tables.css +0 -50
  124. data/guides/assets/stylesheets/style.css +0 -13
  125. data/guides/assets/stylesheets/syntaxhighlighter/shCore.css +0 -226
  126. data/guides/assets/stylesheets/syntaxhighlighter/shCoreDefault.css +0 -328
  127. data/guides/assets/stylesheets/syntaxhighlighter/shCoreDjango.css +0 -331
  128. data/guides/assets/stylesheets/syntaxhighlighter/shCoreEclipse.css +0 -339
  129. data/guides/assets/stylesheets/syntaxhighlighter/shCoreEmacs.css +0 -324
  130. data/guides/assets/stylesheets/syntaxhighlighter/shCoreFadeToGrey.css +0 -328
  131. data/guides/assets/stylesheets/syntaxhighlighter/shCoreMDUltra.css +0 -324
  132. data/guides/assets/stylesheets/syntaxhighlighter/shCoreMidnight.css +0 -324
  133. data/guides/assets/stylesheets/syntaxhighlighter/shCoreRDark.css +0 -324
  134. data/guides/assets/stylesheets/syntaxhighlighter/shThemeDefault.css +0 -117
  135. data/guides/assets/stylesheets/syntaxhighlighter/shThemeDjango.css +0 -120
  136. data/guides/assets/stylesheets/syntaxhighlighter/shThemeEclipse.css +0 -128
  137. data/guides/assets/stylesheets/syntaxhighlighter/shThemeEmacs.css +0 -113
  138. data/guides/assets/stylesheets/syntaxhighlighter/shThemeFadeToGrey.css +0 -117
  139. data/guides/assets/stylesheets/syntaxhighlighter/shThemeMDUltra.css +0 -113
  140. data/guides/assets/stylesheets/syntaxhighlighter/shThemeMidnight.css +0 -113
  141. data/guides/assets/stylesheets/syntaxhighlighter/shThemeRDark.css +0 -113
  142. data/guides/assets/stylesheets/syntaxhighlighter/shThemeRailsGuides.css +0 -116
  143. data/guides/bug_report_templates/action_controller_gem.rb +0 -47
  144. data/guides/bug_report_templates/action_controller_master.rb +0 -54
  145. data/guides/bug_report_templates/active_record_gem.rb +0 -40
  146. data/guides/bug_report_templates/active_record_master.rb +0 -49
  147. data/guides/bug_report_templates/generic_gem.rb +0 -15
  148. data/guides/bug_report_templates/generic_master.rb +0 -26
  149. data/guides/rails_guides/generator.rb +0 -248
  150. data/guides/rails_guides/helpers.rb +0 -53
  151. data/guides/rails_guides/indexer.rb +0 -68
  152. data/guides/rails_guides/kindle.rb +0 -119
  153. data/guides/rails_guides/levenshtein.rb +0 -37
  154. data/guides/rails_guides/markdown/renderer.rb +0 -82
  155. data/guides/rails_guides/markdown.rb +0 -167
  156. data/guides/rails_guides.rb +0 -63
  157. data/guides/source/2_2_release_notes.md +0 -435
  158. data/guides/source/2_3_release_notes.md +0 -621
  159. data/guides/source/3_0_release_notes.md +0 -611
  160. data/guides/source/3_1_release_notes.md +0 -559
  161. data/guides/source/3_2_release_notes.md +0 -568
  162. data/guides/source/4_0_release_notes.md +0 -279
  163. data/guides/source/4_1_release_notes.md +0 -730
  164. data/guides/source/4_2_release_notes.md +0 -877
  165. data/guides/source/_license.html.erb +0 -2
  166. data/guides/source/_welcome.html.erb +0 -23
  167. data/guides/source/action_controller_overview.md +0 -1192
  168. data/guides/source/action_mailer_basics.md +0 -757
  169. data/guides/source/action_view_overview.md +0 -1561
  170. data/guides/source/active_job_basics.md +0 -339
  171. data/guides/source/active_model_basics.md +0 -554
  172. data/guides/source/active_record_basics.md +0 -374
  173. data/guides/source/active_record_callbacks.md +0 -413
  174. data/guides/source/active_record_migrations.md +0 -1018
  175. data/guides/source/active_record_postgresql.md +0 -433
  176. data/guides/source/active_record_querying.md +0 -1781
  177. data/guides/source/active_record_validations.md +0 -1179
  178. data/guides/source/active_support_core_extensions.md +0 -3857
  179. data/guides/source/active_support_instrumentation.md +0 -488
  180. data/guides/source/api_documentation_guidelines.md +0 -361
  181. data/guides/source/asset_pipeline.md +0 -1304
  182. data/guides/source/association_basics.md +0 -2245
  183. data/guides/source/autoloading_and_reloading_constants.md +0 -1311
  184. data/guides/source/caching_with_rails.md +0 -379
  185. data/guides/source/command_line.md +0 -625
  186. data/guides/source/configuring.md +0 -1072
  187. data/guides/source/contributing_to_ruby_on_rails.md +0 -628
  188. data/guides/source/credits.html.erb +0 -80
  189. data/guides/source/debugging_rails_applications.md +0 -861
  190. data/guides/source/development_dependencies_install.md +0 -289
  191. data/guides/source/documents.yaml +0 -205
  192. data/guides/source/engines.md +0 -1412
  193. data/guides/source/form_helpers.md +0 -1024
  194. data/guides/source/generators.md +0 -676
  195. data/guides/source/getting_started.md +0 -2086
  196. data/guides/source/i18n.md +0 -1087
  197. data/guides/source/index.html.erb +0 -28
  198. data/guides/source/initialization.md +0 -704
  199. data/guides/source/kindle/copyright.html.erb +0 -1
  200. data/guides/source/kindle/layout.html.erb +0 -27
  201. data/guides/source/kindle/rails_guides.opf.erb +0 -52
  202. data/guides/source/kindle/toc.html.erb +0 -24
  203. data/guides/source/kindle/toc.ncx.erb +0 -64
  204. data/guides/source/kindle/welcome.html.erb +0 -5
  205. data/guides/source/layout.html.erb +0 -140
  206. data/guides/source/layouts_and_rendering.md +0 -1227
  207. data/guides/source/maintenance_policy.md +0 -78
  208. data/guides/source/nested_model_forms.md +0 -228
  209. data/guides/source/plugins.md +0 -444
  210. data/guides/source/rails_application_templates.md +0 -266
  211. data/guides/source/rails_on_rack.md +0 -336
  212. data/guides/source/routing.md +0 -1155
  213. data/guides/source/ruby_on_rails_guides_guidelines.md +0 -127
  214. data/guides/source/security.md +0 -1024
  215. data/guides/source/testing.md +0 -1132
  216. data/guides/source/upgrading_ruby_on_rails.md +0 -1186
  217. data/guides/source/working_with_javascript_in_rails.md +0 -407
  218. data/guides/w3c_validator.rb +0 -97
@@ -1,1192 +0,0 @@
1
- Action Controller Overview
2
- ==========================
3
-
4
- In this guide you will learn how controllers work and how they fit into the request cycle in your application.
5
-
6
- After reading this guide, you will know:
7
-
8
- * How to follow the flow of a request through a controller.
9
- * How to restrict parameters passed to your controller.
10
- * Why and how to store data in the session or cookies.
11
- * How to work with filters to execute code during request processing.
12
- * How to use Action Controller's built-in HTTP authentication.
13
- * How to stream data directly to the user's browser.
14
- * How to filter sensitive parameters so they do not appear in the application's log.
15
- * How to deal with exceptions that may be raised during request processing.
16
-
17
- --------------------------------------------------------------------------------
18
-
19
- What Does a Controller Do?
20
- --------------------------
21
-
22
- 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 straightforward as possible.
23
-
24
- For most conventional [RESTful](http://en.wikipedia.org/wiki/Representational_state_transfer) 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.
25
-
26
- 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.
27
-
28
- NOTE: For more details on the routing process, see [Rails Routing from the Outside In](routing.html).
29
-
30
- Controller Naming Convention
31
- ----------------------------
32
-
33
- The naming convention of controllers in Rails favors pluralization of the last word in the controller's name, although it is not strictly required (e.g. `ApplicationController`). For example, `ClientsController` is preferable to `ClientController`, `SiteAdminsController` is preferable to `SiteAdminController` or `SitesAdminsController`, and so on.
34
-
35
- Following this convention will allow you to use the default route generators (e.g. `resources`, etc) without needing to qualify each `:path` or `:controller`, and keeps URL and path helpers' usage consistent throughout your application. See [Layouts & Rendering Guide](layouts_and_rendering.html) for more details.
36
-
37
- NOTE: The controller naming convention differs from the naming convention of models, which are expected to be named in singular form.
38
-
39
-
40
- Methods and Actions
41
- -------------------
42
-
43
- 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 method with the same name as the action.
44
-
45
- ```ruby
46
- class ClientsController < ApplicationController
47
- def new
48
- end
49
- end
50
- ```
51
-
52
- As an example, if a user goes to `/clients/new` in your application to add a new client, Rails will create an instance of `ClientsController` and run the `new` method. Note that the empty method from the example above would work just fine because Rails will by default render the `new.html.erb` view unless the action says otherwise. The `new` method could make available to the view a `@client` instance variable by creating a new `Client`:
53
-
54
- ```ruby
55
- def new
56
- @client = Client.new
57
- end
58
- ```
59
-
60
- The [Layouts & Rendering Guide](layouts_and_rendering.html) explains this in more detail.
61
-
62
- `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.
63
-
64
- 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.
65
-
66
- Parameters
67
- ----------
68
-
69
- 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 an 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 `params` hash in your controller:
70
-
71
- ```ruby
72
- class ClientsController < ApplicationController
73
- # This action uses query string parameters because it gets run
74
- # by an HTTP GET request, but this does not make any difference
75
- # to the way in which the parameters are accessed. The URL for
76
- # this action would look like this in order to list activated
77
- # clients: /clients?status=activated
78
- def index
79
- if params[:status] == "activated"
80
- @clients = Client.activated
81
- else
82
- @clients = Client.inactivated
83
- end
84
- end
85
-
86
- # This action uses POST parameters. They are most likely coming
87
- # from an HTML form which the user has submitted. The URL for
88
- # this RESTful request will be "/clients", and the data will be
89
- # sent as part of the request body.
90
- def create
91
- @client = Client.new(params[:client])
92
- if @client.save
93
- redirect_to @client
94
- else
95
- # This line overrides the default rendering behavior, which
96
- # would have been to render the "create" view.
97
- render "new"
98
- end
99
- end
100
- end
101
- ```
102
-
103
- ### Hash and Array Parameters
104
-
105
- 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 an empty pair of square brackets "[]" to the key name:
106
-
107
- ```
108
- GET /clients?ids[]=1&ids[]=2&ids[]=3
109
- ```
110
-
111
- NOTE: The actual URL 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.
112
-
113
- The value of `params[:ids]` will now be `["1", "2", "3"]`. Note that parameter values are always strings; Rails makes no attempt to guess or cast the type.
114
-
115
- NOTE: Values such as `[]`, `[nil]` or `[nil, nil, ...]` in `params` are replaced
116
- with `nil` for security reasons by default. See [Security Guide](security.html#unsafe-query-generation)
117
- for more information.
118
-
119
- To send a hash you include the key name inside the brackets:
120
-
121
- ```html
122
- <form accept-charset="UTF-8" action="/clients" method="post">
123
- <input type="text" name="client[name]" value="Acme" />
124
- <input type="text" name="client[phone]" value="12345" />
125
- <input type="text" name="client[address][postcode]" value="12345" />
126
- <input type="text" name="client[address][city]" value="Carrot City" />
127
- </form>
128
- ```
129
-
130
- When this form is submitted, the value of `params[:client]` will be `{ "name" => "Acme", "phone" => "12345", "address" => { "postcode" => "12345", "city" => "Carrot City" } }`. Note the nested hash in `params[:client][:address]`.
131
-
132
- Note that the `params` hash is actually an instance of `ActiveSupport::HashWithIndifferentAccess`, which acts like a hash but lets you use symbols and strings interchangeably as keys.
133
-
134
- ### JSON parameters
135
-
136
- If you're writing a web service application, you might find yourself more comfortable accepting parameters in JSON format. If the "Content-Type" header of your request is set to "application/json", Rails will automatically convert your parameters into the `params` hash, which you can access as you would normally.
137
-
138
- So for example, if you are sending this JSON content:
139
-
140
- ```json
141
- { "company": { "name": "acme", "address": "123 Carrot Street" } }
142
- ```
143
-
144
- You'll get `params[:company]` as `{ "name" => "acme", "address" => "123 Carrot Street" }`.
145
-
146
- Also, if you've turned on `config.wrap_parameters` in your initializer or calling `wrap_parameters` in your controller, you can safely omit the root element in the JSON 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:
147
-
148
- ```json
149
- { "name": "acme", "address": "123 Carrot Street" }
150
- ```
151
-
152
- And assume that you're sending the data to `CompaniesController`, it would then be wrapped in `:company` key like this:
153
-
154
- ```ruby
155
- { name: "acme", address: "123 Carrot Street", company: { name: "acme", address: "123 Carrot Street" } }
156
- ```
157
-
158
- You can customize the name of the key or specific parameters you want to wrap by consulting the [API documentation](http://api.rubyonrails.org/classes/ActionController/ParamsWrapper.html)
159
-
160
- NOTE: Support for parsing XML parameters has been extracted into a gem named `actionpack-xml_parser`
161
-
162
- ### Routing Parameters
163
-
164
- The `params` hash will always contain the `:controller` and `:action` keys, but you should use the methods `controller_name` and `action_name` instead to access these values. Any other parameters defined by the routing, such as `:id` 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 `:status` parameter in a "pretty" URL:
165
-
166
- ```ruby
167
- get '/clients/:status' => 'clients#index', foo: 'bar'
168
- ```
169
-
170
- In this case, when a user opens the URL `/clients/active`, `params[:status]` will be set to "active". When this route is used, `params[:foo]` will also be set to "bar" just like it was passed in the query string. In the same way `params[:action]` will contain "index".
171
-
172
- ### `default_url_options`
173
-
174
- You can set global default parameters for URL generation by defining a method called `default_url_options` in your controller. Such a method must return a hash with the desired defaults, whose keys must be symbols:
175
-
176
- ```ruby
177
- class ApplicationController < ActionController::Base
178
- def default_url_options
179
- { locale: I18n.locale }
180
- end
181
- end
182
- ```
183
-
184
- These options will be used as a starting point when generating URLs, so it's possible they'll be overridden by the options passed in `url_for` calls.
185
-
186
- If you define `default_url_options` in `ApplicationController`, as in the example above, it would be used for all URL generation. The method can also be defined in one specific controller, in which case it only affects URLs generated there.
187
-
188
- ### Strong Parameters
189
-
190
- With strong parameters, Action Controller parameters are forbidden to
191
- be used in Active Model mass assignments until they have been
192
- whitelisted. This means you'll have to make a conscious choice about
193
- which attributes to allow for mass updating and thus prevent
194
- accidentally exposing that which shouldn't be exposed.
195
-
196
- In addition, parameters can be marked as required and flow through a
197
- predefined raise/rescue flow to end up as a 400 Bad Request with no
198
- effort.
199
-
200
- ```ruby
201
- class PeopleController < ActionController::Base
202
- # This will raise an ActiveModel::ForbiddenAttributes exception
203
- # because it's using mass assignment without an explicit permit
204
- # step.
205
- def create
206
- Person.create(params[:person])
207
- end
208
-
209
- # This will pass with flying colors as long as there's a person key
210
- # in the parameters, otherwise it'll raise a
211
- # ActionController::ParameterMissing exception, which will get
212
- # caught by ActionController::Base and turned into that 400 Bad
213
- # Request reply.
214
- def update
215
- person = current_account.people.find(params[:id])
216
- person.update!(person_params)
217
- redirect_to person
218
- end
219
-
220
- private
221
- # Using a private method to encapsulate the permissible parameters
222
- # is just a good pattern since you'll be able to reuse the same
223
- # permit list between create and update. Also, you can specialize
224
- # this method with per-user checking of permissible attributes.
225
- def person_params
226
- params.require(:person).permit(:name, :age)
227
- end
228
- end
229
- ```
230
-
231
- #### Permitted Scalar Values
232
-
233
- Given
234
-
235
- ```ruby
236
- params.permit(:id)
237
- ```
238
-
239
- the key `:id` will pass the whitelisting if it appears in `params` and
240
- it has a permitted scalar value associated. Otherwise the key is going
241
- to be filtered out, so arrays, hashes, or any other objects cannot be
242
- injected.
243
-
244
- The permitted scalar types are `String`, `Symbol`, `NilClass`,
245
- `Numeric`, `TrueClass`, `FalseClass`, `Date`, `Time`, `DateTime`,
246
- `StringIO`, `IO`, `ActionDispatch::Http::UploadedFile` and
247
- `Rack::Test::UploadedFile`.
248
-
249
- To declare that the value in `params` must be an array of permitted
250
- scalar values map the key to an empty array:
251
-
252
- ```ruby
253
- params.permit(id: [])
254
- ```
255
-
256
- To whitelist an entire hash of parameters, the `permit!` method can be
257
- used:
258
-
259
- ```ruby
260
- params.require(:log_entry).permit!
261
- ```
262
-
263
- This will mark the `:log_entry` parameters hash and any sub-hash of it
264
- permitted. Extreme care should be taken when using `permit!` as it
265
- will allow all current and future model attributes to be
266
- mass-assigned.
267
-
268
- #### Nested Parameters
269
-
270
- You can also use permit on nested parameters, like:
271
-
272
- ```ruby
273
- params.permit(:name, { emails: [] },
274
- friends: [ :name,
275
- { family: [ :name ], hobbies: [] }])
276
- ```
277
-
278
- This declaration whitelists the `name`, `emails` and `friends`
279
- attributes. It is expected that `emails` will be an array of permitted
280
- scalar values and that `friends` will be an array of resources with
281
- specific attributes : they should have a `name` attribute (any
282
- permitted scalar values allowed), a `hobbies` attribute as an array of
283
- permitted scalar values, and a `family` attribute which is restricted
284
- to having a `name` (any permitted scalar values allowed, too).
285
-
286
- #### More Examples
287
-
288
- You want to also use the permitted attributes in the `new`
289
- action. This raises the problem that you can't use `require` on the
290
- root key because normally it does not exist when calling `new`:
291
-
292
- ```ruby
293
- # using `fetch` you can supply a default and use
294
- # the Strong Parameters API from there.
295
- params.fetch(:blog, {}).permit(:title, :author)
296
- ```
297
-
298
- `accepts_nested_attributes_for` allows you to update and destroy
299
- associated records. This is based on the `id` and `_destroy`
300
- parameters:
301
-
302
- ```ruby
303
- # permit :id and :_destroy
304
- params.require(:author).permit(:name, books_attributes: [:title, :id, :_destroy])
305
- ```
306
-
307
- Hashes with integer keys are treated differently and you can declare
308
- the attributes as if they were direct children. You get these kinds of
309
- parameters when you use `accepts_nested_attributes_for` in combination
310
- with a `has_many` association:
311
-
312
- ```ruby
313
- # To whitelist the following data:
314
- # {"book" => {"title" => "Some Book",
315
- # "chapters_attributes" => { "1" => {"title" => "First Chapter"},
316
- # "2" => {"title" => "Second Chapter"}}}}
317
-
318
- params.require(:book).permit(:title, chapters_attributes: [:title])
319
- ```
320
-
321
- #### Outside the Scope of Strong Parameters
322
-
323
- The strong parameter API was designed with the most common use cases
324
- in mind. It is not meant as a silver bullet to handle all your
325
- whitelisting problems. However you can easily mix the API with your
326
- own code to adapt to your situation.
327
-
328
- Imagine a scenario where you have parameters representing a product
329
- name and a hash of arbitrary data associated with that product, and
330
- you want to whitelist the product name attribute but also the whole
331
- data hash. The strong parameters API doesn't let you directly
332
- whitelist the whole of a nested hash with any keys, but you can use
333
- the keys of your nested hash to declare what to whitelist:
334
-
335
- ```ruby
336
- def product_params
337
- params.require(:product).permit(:name, data: params[:product][:data].try(:keys))
338
- end
339
- ```
340
-
341
- Session
342
- -------
343
-
344
- 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:
345
-
346
- * `ActionDispatch::Session::CookieStore` - Stores everything on the client.
347
- * `ActionDispatch::Session::CacheStore` - Stores the data in the Rails cache.
348
- * `ActionDispatch::Session::ActiveRecordStore` - Stores the data in a database using Active Record. (require `activerecord-session_store` gem).
349
- * `ActionDispatch::Session::MemCacheStore` - Stores the data in a memcached cluster (this is a legacy implementation; consider using CacheStore instead).
350
-
351
- 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 URL as this is less secure).
352
-
353
- 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. And it is also encrypted so anyone with access to it can't read its contents. (Rails will not accept it if it has been edited).
354
-
355
- 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.
356
-
357
- 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.
358
-
359
- Read more about session storage in the [Security Guide](security.html).
360
-
361
- If you need a different session storage mechanism, you can change it in the `config/initializers/session_store.rb` file:
362
-
363
- ```ruby
364
- # Use the database for sessions instead of the cookie-based default,
365
- # which shouldn't be used to store highly confidential information
366
- # (create the session table with "rails g active_record:session_migration")
367
- # Rails.application.config.session_store :active_record_store
368
- ```
369
-
370
- Rails sets up a session key (the name of the cookie) when signing the session data. These can also be changed in `config/initializers/session_store.rb`:
371
-
372
- ```ruby
373
- # Be sure to restart your server when you modify this file.
374
- Rails.application.config.session_store :cookie_store, key: '_your_app_session'
375
- ```
376
-
377
- You can also pass a `:domain` key and specify the domain name for the cookie:
378
-
379
- ```ruby
380
- # Be sure to restart your server when you modify this file.
381
- Rails.application.config.session_store :cookie_store, key: '_your_app_session', domain: ".example.com"
382
- ```
383
-
384
- Rails sets up (for the CookieStore) a secret key used for signing the session data. This can be changed in `config/secrets.yml`
385
-
386
- ```ruby
387
- # Be sure to restart your server when you modify this file.
388
-
389
- # Your secret key is used for verifying the integrity of signed cookies.
390
- # If you change this key, all old signed cookies will become invalid!
391
-
392
- # Make sure the secret is at least 30 characters and all random,
393
- # no regular words or you'll be exposed to dictionary attacks.
394
- # You can use `rake secret` to generate a secure secret key.
395
-
396
- # Make sure the secrets in this file are kept private
397
- # if you're sharing your code publicly.
398
-
399
- development:
400
- secret_key_base: a75d...
401
-
402
- test:
403
- secret_key_base: 492f...
404
-
405
- # Do not keep production secrets in the repository,
406
- # instead read values from the environment.
407
- production:
408
- secret_key_base: <%= ENV["SECRET_KEY_BASE"] %>
409
- ```
410
-
411
- NOTE: Changing the secret when using the `CookieStore` will invalidate all existing sessions.
412
-
413
- ### Accessing the Session
414
-
415
- In your controller you can access the session through the `session` instance method.
416
-
417
- NOTE: 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.
418
-
419
- Session values are stored using key/value pairs like a hash:
420
-
421
- ```ruby
422
- class ApplicationController < ActionController::Base
423
-
424
- private
425
-
426
- # Finds the User with the ID stored in the session with the key
427
- # :current_user_id This is a common way to handle user login in
428
- # a Rails application; logging in sets the session value and
429
- # logging out removes it.
430
- def current_user
431
- @_current_user ||= session[:current_user_id] &&
432
- User.find_by(id: session[:current_user_id])
433
- end
434
- end
435
- ```
436
-
437
- To store something in the session, just assign it to the key like a hash:
438
-
439
- ```ruby
440
- class LoginsController < ApplicationController
441
- # "Create" a login, aka "log the user in"
442
- def create
443
- if user = User.authenticate(params[:username], params[:password])
444
- # Save the user ID in the session so it can be used in
445
- # subsequent requests
446
- session[:current_user_id] = user.id
447
- redirect_to root_url
448
- end
449
- end
450
- end
451
- ```
452
-
453
- To remove something from the session, assign that key to be `nil`:
454
-
455
- ```ruby
456
- class LoginsController < ApplicationController
457
- # "Delete" a login, aka "log the user out"
458
- def destroy
459
- # Remove the user id from the session
460
- @_current_user = session[:current_user_id] = nil
461
- redirect_to root_url
462
- end
463
- end
464
- ```
465
-
466
- To reset the entire session, use `reset_session`.
467
-
468
- ### The Flash
469
-
470
- 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 passing error messages etc.
471
-
472
- It is accessed in much the same way as the session, as a hash (it's a [FlashHash](http://api.rubyonrails.org/classes/ActionDispatch/Flash/FlashHash.html) instance).
473
-
474
- 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:
475
-
476
- ```ruby
477
- class LoginsController < ApplicationController
478
- def destroy
479
- session[:current_user_id] = nil
480
- flash[:notice] = "You have successfully logged out."
481
- redirect_to root_url
482
- end
483
- end
484
- ```
485
-
486
- Note that it is also possible to assign a flash message as part of the redirection. You can assign `:notice`, `:alert` or the general purpose `:flash`:
487
-
488
- ```ruby
489
- redirect_to root_url, notice: "You have successfully logged out."
490
- redirect_to root_url, alert: "You're stuck here!"
491
- redirect_to root_url, flash: { referral_code: 1234 }
492
- ```
493
-
494
- The `destroy` action redirects to the application's `root_url`, 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 any error alerts or notices from the flash in the application's layout:
495
-
496
- ```erb
497
- <html>
498
- <!-- <head/> -->
499
- <body>
500
- <% flash.each do |name, msg| -%>
501
- <%= content_tag :div, msg, class: name %>
502
- <% end -%>
503
-
504
- <!-- more content -->
505
- </body>
506
- </html>
507
- ```
508
-
509
- This way, if an action sets a notice or an alert message, the layout will display it automatically.
510
-
511
- You can pass anything that the session can store; you're not limited to notices and alerts:
512
-
513
- ```erb
514
- <% if flash[:just_signed_up] %>
515
- <p class="welcome">Welcome to our site!</p>
516
- <% end %>
517
- ```
518
-
519
- If you want a flash value to be carried over to another request, use the `keep` method:
520
-
521
- ```ruby
522
- class MainController < ApplicationController
523
- # Let's say this action corresponds to root_url, but you want
524
- # all requests here to be redirected to UsersController#index.
525
- # If an action sets the flash and redirects here, the values
526
- # would normally be lost when another redirect happens, but you
527
- # can use 'keep' to make it persist for another request.
528
- def index
529
- # Will persist all flash values.
530
- flash.keep
531
-
532
- # You can also use a key to keep only some kind of value.
533
- # flash.keep(:notice)
534
- redirect_to users_url
535
- end
536
- end
537
- ```
538
-
539
- #### `flash.now`
540
-
541
- 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 `create` action fails to save a resource and you render the `new` 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 `flash.now` in the same way you use the normal `flash`:
542
-
543
- ```ruby
544
- class ClientsController < ApplicationController
545
- def create
546
- @client = Client.new(params[:client])
547
- if @client.save
548
- # ...
549
- else
550
- flash.now[:error] = "Could not save client"
551
- render action: "new"
552
- end
553
- end
554
- end
555
- ```
556
-
557
- Cookies
558
- -------
559
-
560
- 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 `cookies` method, which - much like the `session` - works like a hash:
561
-
562
- ```ruby
563
- class CommentsController < ApplicationController
564
- def new
565
- # Auto-fill the commenter's name if it has been stored in a cookie
566
- @comment = Comment.new(author: cookies[:commenter_name])
567
- end
568
-
569
- def create
570
- @comment = Comment.new(params[:comment])
571
- if @comment.save
572
- flash[:notice] = "Thanks for your comment!"
573
- if params[:remember_name]
574
- # Remember the commenter's name.
575
- cookies[:commenter_name] = @comment.author
576
- else
577
- # Delete cookie for the commenter's name cookie, if any.
578
- cookies.delete(:commenter_name)
579
- end
580
- redirect_to @comment.article
581
- else
582
- render action: "new"
583
- end
584
- end
585
- end
586
- ```
587
-
588
- Note that while for session values you set the key to `nil`, to delete a cookie value you should use `cookies.delete(:key)`.
589
-
590
- Rails also provides a signed cookie jar and an encrypted cookie jar for storing
591
- sensitive data. The signed cookie jar appends a cryptographic signature on the
592
- cookie values to protect their integrity. The encrypted cookie jar encrypts the
593
- values in addition to signing them, so that they cannot be read by the end user.
594
- Refer to the [API documentation](http://api.rubyonrails.org/classes/ActionDispatch/Cookies.html)
595
- for more details.
596
-
597
- These special cookie jars use a serializer to serialize the assigned values into
598
- strings and deserializes them into Ruby objects on read.
599
-
600
- You can specify what serializer to use:
601
-
602
- ```ruby
603
- Rails.application.config.action_dispatch.cookies_serializer = :json
604
- ```
605
-
606
- The default serializer for new applications is `:json`. For compatibility with
607
- old applications with existing cookies, `:marshal` is used when `serializer`
608
- option is not specified.
609
-
610
- You may also set this option to `:hybrid`, in which case Rails would transparently
611
- deserialize existing (`Marshal`-serialized) cookies on read and re-write them in
612
- the `JSON` format. This is useful for migrating existing applications to the
613
- `:json` serializer.
614
-
615
- It is also possible to pass a custom serializer that responds to `load` and
616
- `dump`:
617
-
618
- ```ruby
619
- Rails.application.config.action_dispatch.cookies_serializer = MyCustomSerializer
620
- ```
621
-
622
- When using the `:json` or `:hybrid` serializer, you should beware that not all
623
- Ruby objects can be serialized as JSON. For example, `Date` and `Time` objects
624
- will be serialized as strings, and `Hash`es will have their keys stringified.
625
-
626
- ```ruby
627
- class CookiesController < ApplicationController
628
- def set_cookie
629
- cookies.encrypted[:expiration_date] = Date.tomorrow # => Thu, 20 Mar 2014
630
- redirect_to action: 'read_cookie'
631
- end
632
-
633
- def read_cookie
634
- cookies.encrypted[:expiration_date] # => "2014-03-20"
635
- end
636
- end
637
- ```
638
-
639
- It's advisable that you only store simple data (strings and numbers) in cookies.
640
- If you have to store complex objects, you would need to handle the conversion
641
- manually when reading the values on subsequent requests.
642
-
643
- If you use the cookie session store, this would apply to the `session` and
644
- `flash` hash as well.
645
-
646
- Rendering XML and JSON data
647
- ---------------------------
648
-
649
- ActionController makes it extremely easy to render `XML` or `JSON` data. If you've generated a controller using scaffolding, it would look something like this:
650
-
651
- ```ruby
652
- class UsersController < ApplicationController
653
- def index
654
- @users = User.all
655
- respond_to do |format|
656
- format.html # index.html.erb
657
- format.xml { render xml: @users}
658
- format.json { render json: @users}
659
- end
660
- end
661
- end
662
- ```
663
-
664
- You may notice in the above code that we're using `render xml: @users`, not `render xml: @users.to_xml`. If the object is not a String, then Rails will automatically invoke `to_xml` for us.
665
-
666
- Filters
667
- -------
668
-
669
- Filters are methods that are run before, after or "around" a controller action.
670
-
671
- Filters are inherited, so if you set a filter on `ApplicationController`, it will be run on every controller in your application.
672
-
673
- "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:
674
-
675
- ```ruby
676
- class ApplicationController < ActionController::Base
677
- before_action :require_login
678
-
679
- private
680
-
681
- def require_login
682
- unless logged_in?
683
- flash[:error] = "You must be logged in to access this section"
684
- redirect_to new_login_url # halts request cycle
685
- end
686
- end
687
- end
688
- ```
689
-
690
- 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.
691
-
692
- In this example the filter is added to `ApplicationController` 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 `skip_before_action`:
693
-
694
- ```ruby
695
- class LoginsController < ApplicationController
696
- skip_before_action :require_login, only: [:new, :create]
697
- end
698
- ```
699
-
700
- Now, the `LoginsController`'s `new` and `create` actions will work as before without requiring the user to be logged in. The `:only` option is used to only skip this filter for these actions, and there is also an `:except` 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.
701
-
702
- ### After Filters and Around Filters
703
-
704
- In addition to "before" filters, you can also run filters after an action has been executed, or both before and after.
705
-
706
- "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.
707
-
708
- "Around" filters are responsible for running their associated actions by yielding, similar to how Rack middlewares work.
709
-
710
- 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:
711
-
712
- ```ruby
713
- class ChangesController < ApplicationController
714
- around_action :wrap_in_transaction, only: :show
715
-
716
- private
717
-
718
- def wrap_in_transaction
719
- ActiveRecord::Base.transaction do
720
- begin
721
- yield
722
- ensure
723
- raise ActiveRecord::Rollback
724
- end
725
- end
726
- end
727
- end
728
- ```
729
-
730
- Note that an "around" filter also wraps rendering. In particular, if in the example above, the view itself reads from the database (e.g. via a scope), it will do so within the transaction and thus present the data to preview.
731
-
732
- You can choose not to yield and build the response yourself, in which case the action will not be run.
733
-
734
- ### Other Ways to Use Filters
735
-
736
- While the most common way to use filters is by creating private methods and using *_action to add them, there are two other ways to do the same thing.
737
-
738
- The first is to use a block directly with the *\_action methods. The block receives the controller as an argument, and the `require_login` filter from above could be rewritten to use a block:
739
-
740
- ```ruby
741
- class ApplicationController < ActionController::Base
742
- before_action do |controller|
743
- unless controller.send(:logged_in?)
744
- flash[:error] = "You must be logged in to access this section"
745
- redirect_to new_login_url
746
- end
747
- end
748
- end
749
- ```
750
-
751
- Note that the filter in this case uses `send` because the `logged_in?` 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.
752
-
753
- 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 cannot 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:
754
-
755
- ```ruby
756
- class ApplicationController < ActionController::Base
757
- before_action LoginFilter
758
- end
759
-
760
- class LoginFilter
761
- def self.before(controller)
762
- unless controller.send(:logged_in?)
763
- controller.flash[:error] = "You must be logged in to access this section"
764
- controller.redirect_to controller.new_login_url
765
- end
766
- end
767
- end
768
- ```
769
-
770
- 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 must implement a method with the same name as the filter, so for the `before_action` filter the class must implement a `before` method, and so on. The `around` method must `yield` to execute the action.
771
-
772
- Request Forgery Protection
773
- --------------------------
774
-
775
- 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.
776
-
777
- 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.
778
-
779
- 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.
780
-
781
- If you generate a form like this:
782
-
783
- ```erb
784
- <%= form_for @user do |f| %>
785
- <%= f.text_field :username %>
786
- <%= f.text_field :password %>
787
- <% end %>
788
- ```
789
-
790
- You will see how the token gets added as a hidden field:
791
-
792
- ```html
793
- <form accept-charset="UTF-8" action="/users/1" method="post">
794
- <input type="hidden"
795
- value="67250ab105eb5ad10851c00a5621854a23af5489"
796
- name="authenticity_token"/>
797
- <!-- fields -->
798
- </form>
799
- ```
800
-
801
- Rails adds this token to every form that's generated using the [form helpers](form_helpers.html), 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 `form_authenticity_token`:
802
-
803
- The `form_authenticity_token` generates a valid authentication token. That's useful in places where Rails does not add it automatically, like in custom Ajax calls.
804
-
805
- The [Security Guide](security.html) has more about this and a lot of other security-related issues that you should be aware of when developing a web application.
806
-
807
- The Request and Response Objects
808
- --------------------------------
809
-
810
- 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 `request` method contains an instance of `AbstractRequest` and the `response` method returns a response object representing what is going to be sent back to the client.
811
-
812
- ### The `request` Object
813
-
814
- 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 [API documentation](http://api.rubyonrails.org/classes/ActionDispatch/Request.html). Among the properties that you can access on this object are:
815
-
816
- | Property of `request` | Purpose |
817
- | ----------------------------------------- | -------------------------------------------------------------------------------- |
818
- | host | The hostname used for this request. |
819
- | domain(n=2) | The hostname's first `n` segments, starting from the right (the TLD). |
820
- | format | The content type requested by the client. |
821
- | method | The HTTP method used for the request. |
822
- | get?, post?, patch?, put?, delete?, head? | Returns true if the HTTP method is GET/POST/PATCH/PUT/DELETE/HEAD. |
823
- | headers | Returns a hash containing the headers associated with the request. |
824
- | port | The port number (integer) used for the request. |
825
- | protocol | Returns a string containing the protocol used plus "://", for example "http://". |
826
- | query_string | The query string part of the URL, i.e., everything after "?". |
827
- | remote_ip | The IP address of the client. |
828
- | url | The entire URL used for the request. |
829
-
830
- #### `path_parameters`, `query_parameters`, and `request_parameters`
831
-
832
- Rails collects all of the parameters sent along with the request in the `params` 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 `query_parameters` hash contains parameters that were sent as part of the query string while the `request_parameters` hash contains parameters sent as part of the post body. The `path_parameters` hash contains parameters that were recognized by the routing as being part of the path leading to this particular controller and action.
833
-
834
- ### The `response` Object
835
-
836
- 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.
837
-
838
- | Property of `response` | Purpose |
839
- | ---------------------- | --------------------------------------------------------------------------------------------------- |
840
- | body | This is the string of data being sent back to the client. This is most often HTML. |
841
- | status | The HTTP status code for the response, like 200 for a successful request or 404 for file not found. |
842
- | location | The URL the client is being redirected to, if any. |
843
- | content_type | The content type of the response. |
844
- | charset | The character set being used for the response. Default is "utf-8". |
845
- | headers | Headers used for the response. |
846
-
847
- #### Setting Custom Headers
848
-
849
- If you want to set custom headers for a response then `response.headers` 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 `response.headers` this way:
850
-
851
- ```ruby
852
- response.headers["Content-Type"] = "application/pdf"
853
- ```
854
-
855
- Note: in the above case it would make more sense to use the `content_type` setter directly.
856
-
857
- HTTP Authentications
858
- --------------------
859
-
860
- Rails comes with two built-in HTTP authentication mechanisms:
861
-
862
- * Basic Authentication
863
- * Digest Authentication
864
-
865
- ### HTTP Basic Authentication
866
-
867
- HTTP basic authentication is an authentication scheme that is supported by the majority of browsers and other HTTP clients. As an example, consider an administration section which will only be available by entering a username and a password into the browser's HTTP basic dialog window. Using the built-in authentication is quite easy and only requires you to use one method, `http_basic_authenticate_with`.
868
-
869
- ```ruby
870
- class AdminsController < ApplicationController
871
- http_basic_authenticate_with name: "humbaba", password: "5baa61e4"
872
- end
873
- ```
874
-
875
- With this in place, you can create namespaced controllers that inherit from `AdminsController`. The filter will thus be run for all actions in those controllers, protecting them with HTTP basic authentication.
876
-
877
- ### HTTP Digest Authentication
878
-
879
- HTTP digest authentication is superior to the basic authentication as it does not require the client to send an unencrypted password over the network (though HTTP basic authentication is safe over HTTPS). Using digest authentication with Rails is quite easy and only requires using one method, `authenticate_or_request_with_http_digest`.
880
-
881
- ```ruby
882
- class AdminsController < ApplicationController
883
- USERS = { "lifo" => "world" }
884
-
885
- before_action :authenticate
886
-
887
- private
888
-
889
- def authenticate
890
- authenticate_or_request_with_http_digest do |username|
891
- USERS[username]
892
- end
893
- end
894
- end
895
- ```
896
-
897
- As seen in the example above, the `authenticate_or_request_with_http_digest` block takes only one argument - the username. And the block returns the password. Returning `false` or `nil` from the `authenticate_or_request_with_http_digest` will cause authentication failure.
898
-
899
- Streaming and File Downloads
900
- ----------------------------
901
-
902
- Sometimes you may want to send a file to the user instead of rendering an HTML page. All controllers in Rails have the `send_data` and the `send_file` methods, which will both stream data to the client. `send_file` 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.
903
-
904
- To stream data to the client, use `send_data`:
905
-
906
- ```ruby
907
- require "prawn"
908
- class ClientsController < ApplicationController
909
- # Generates a PDF document with information on the client and
910
- # returns it. The user will get the PDF as a file download.
911
- def download_pdf
912
- client = Client.find(params[:id])
913
- send_data generate_pdf(client),
914
- filename: "#{client.name}.pdf",
915
- type: "application/pdf"
916
- end
917
-
918
- private
919
-
920
- def generate_pdf(client)
921
- Prawn::Document.new do
922
- text client.name, align: :center
923
- text "Address: #{client.address}"
924
- text "Email: #{client.email}"
925
- end.render
926
- end
927
- end
928
- ```
929
-
930
- The `download_pdf` action in the example above will call a private method which actually generates the 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 `:disposition` option to "inline". The opposite and default value for this option is "attachment".
931
-
932
- ### Sending Files
933
-
934
- If you want to send a file that already exists on disk, use the `send_file` method.
935
-
936
- ```ruby
937
- class ClientsController < ApplicationController
938
- # Stream a file that has already been generated and stored on disk.
939
- def download_pdf
940
- client = Client.find(params[:id])
941
- send_file("#{Rails.root}/files/clients/#{client.id}.pdf",
942
- filename: "#{client.name}.pdf",
943
- type: "application/pdf")
944
- end
945
- end
946
- ```
947
-
948
- 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 `:stream` option or adjust the block size with the `:buffer_size` option.
949
-
950
- If `:type` is not specified, it will be guessed from the file extension specified in `:filename`. If the content type is not registered for the extension, `application/octet-stream` will be used.
951
-
952
- WARNING: 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.
953
-
954
- TIP: 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.
955
-
956
- ### RESTful Downloads
957
-
958
- While `send_data` 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 `show` action, without any streaming:
959
-
960
- ```ruby
961
- class ClientsController < ApplicationController
962
- # The user can request to receive this resource as HTML or PDF.
963
- def show
964
- @client = Client.find(params[:id])
965
-
966
- respond_to do |format|
967
- format.html
968
- format.pdf { render pdf: generate_pdf(@client) }
969
- end
970
- end
971
- end
972
- ```
973
-
974
- 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 `config/initializers/mime_types.rb`:
975
-
976
- ```ruby
977
- Mime::Type.register "application/pdf", :pdf
978
- ```
979
-
980
- NOTE: Configuration files are not reloaded on each request, so you have to restart the server in order for their changes to take effect.
981
-
982
- Now the user can request to get a PDF version of a client just by adding ".pdf" to the URL:
983
-
984
- ```bash
985
- GET /clients/1.pdf
986
- ```
987
-
988
- ### Live Streaming of Arbitrary Data
989
-
990
- Rails allows you to stream more than just files. In fact, you can stream anything
991
- you would like in a response object. The `ActionController::Live` module allows
992
- you to create a persistent connection with a browser. Using this module, you will
993
- be able to send arbitrary data to the browser at specific points in time.
994
-
995
- #### Incorporating Live Streaming
996
-
997
- Including `ActionController::Live` inside of your controller class will provide
998
- all actions inside of the controller the ability to stream data. You can mix in
999
- the module like so:
1000
-
1001
- ```ruby
1002
- class MyController < ActionController::Base
1003
- include ActionController::Live
1004
-
1005
- def stream
1006
- response.headers['Content-Type'] = 'text/event-stream'
1007
- 100.times {
1008
- response.stream.write "hello world\n"
1009
- sleep 1
1010
- }
1011
- ensure
1012
- response.stream.close
1013
- end
1014
- end
1015
- ```
1016
-
1017
- The above code will keep a persistent connection with the browser and send 100
1018
- messages of `"hello world\n"`, each one second apart.
1019
-
1020
- There are a couple of things to notice in the above example. We need to make
1021
- sure to close the response stream. Forgetting to close the stream will leave
1022
- the socket open forever. We also have to set the content type to `text/event-stream`
1023
- before we write to the response stream. This is because headers cannot be written
1024
- after the response has been committed (when `response.committed` returns a truthy
1025
- value), which occurs when you `write` or `commit` the response stream.
1026
-
1027
- #### Example Usage
1028
-
1029
- Let's suppose that you were making a Karaoke machine and a user wants to get the
1030
- lyrics for a particular song. Each `Song` has a particular number of lines and
1031
- each line takes time `num_beats` to finish singing.
1032
-
1033
- If we wanted to return the lyrics in Karaoke fashion (only sending the line when
1034
- the singer has finished the previous line), then we could use `ActionController::Live`
1035
- as follows:
1036
-
1037
- ```ruby
1038
- class LyricsController < ActionController::Base
1039
- include ActionController::Live
1040
-
1041
- def show
1042
- response.headers['Content-Type'] = 'text/event-stream'
1043
- song = Song.find(params[:id])
1044
-
1045
- song.each do |line|
1046
- response.stream.write line.lyrics
1047
- sleep line.num_beats
1048
- end
1049
- ensure
1050
- response.stream.close
1051
- end
1052
- end
1053
- ```
1054
-
1055
- The above code sends the next line only after the singer has completed the previous
1056
- line.
1057
-
1058
- #### Streaming Considerations
1059
-
1060
- Streaming arbitrary data is an extremely powerful tool. As shown in the previous
1061
- examples, you can choose when and what to send across a response stream. However,
1062
- you should also note the following things:
1063
-
1064
- * Each response stream creates a new thread and copies over the thread local
1065
- variables from the original thread. Having too many thread local variables can
1066
- negatively impact performance. Similarly, a large number of threads can also
1067
- hinder performance.
1068
- * Failing to close the response stream will leave the corresponding socket open
1069
- forever. Make sure to call `close` whenever you are using a response stream.
1070
- * WEBrick servers buffer all responses, and so including `ActionController::Live`
1071
- will not work. You must use a web server which does not automatically buffer
1072
- responses.
1073
-
1074
- Log Filtering
1075
- -------------
1076
-
1077
- Rails keeps a log file for each environment 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.
1078
-
1079
- ### Parameters Filtering
1080
-
1081
- You can filter out sensitive request parameters from your log files by appending them to `config.filter_parameters` in the application configuration. These parameters will be marked [FILTERED] in the log.
1082
-
1083
- ```ruby
1084
- config.filter_parameters << :password
1085
- ```
1086
-
1087
- ### Redirects Filtering
1088
-
1089
- Sometimes it's desirable to filter out from log files some sensitive locations your application is redirecting to.
1090
- You can do that by using the `config.filter_redirect` configuration option:
1091
-
1092
- ```ruby
1093
- config.filter_redirect << 's3.amazonaws.com'
1094
- ```
1095
-
1096
- You can set it to a String, a Regexp, or an array of both.
1097
-
1098
- ```ruby
1099
- config.filter_redirect.concat ['s3.amazonaws.com', /private_path/]
1100
- ```
1101
-
1102
- Matching URLs will be marked as '[FILTERED]'.
1103
-
1104
- Rescue
1105
- ------
1106
-
1107
- 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.
1108
-
1109
- 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:
1110
-
1111
- ### The Default 500 and 404 Templates
1112
-
1113
- 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 `public` folder, in `404.html` and `500.html` 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.
1114
-
1115
- ### `rescue_from`
1116
-
1117
- If you want to do something a bit more elaborate when catching errors, you can use `rescue_from`, which handles exceptions of a certain type (or multiple types) in an entire controller and its subclasses.
1118
-
1119
- When an exception occurs which is caught by a `rescue_from` directive, the exception object is passed to the handler. The handler can be a method or a `Proc` object passed to the `:with` option. You can also use a block directly instead of an explicit `Proc` object.
1120
-
1121
- Here's how you can use `rescue_from` to intercept all `ActiveRecord::RecordNotFound` errors and do something with them.
1122
-
1123
- ```ruby
1124
- class ApplicationController < ActionController::Base
1125
- rescue_from ActiveRecord::RecordNotFound, with: :record_not_found
1126
-
1127
- private
1128
-
1129
- def record_not_found
1130
- render plain: "404 Not Found", status: 404
1131
- end
1132
- end
1133
- ```
1134
-
1135
- 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:
1136
-
1137
- ```ruby
1138
- class ApplicationController < ActionController::Base
1139
- rescue_from User::NotAuthorized, with: :user_not_authorized
1140
-
1141
- private
1142
-
1143
- def user_not_authorized
1144
- flash[:error] = "You don't have access to this section."
1145
- redirect_to :back
1146
- end
1147
- end
1148
-
1149
- class ClientsController < ApplicationController
1150
- # Check that the user has the right authorization to access clients.
1151
- before_action :check_authorization
1152
-
1153
- # Note how the actions don't have to worry about all the auth stuff.
1154
- def edit
1155
- @client = Client.find(params[:id])
1156
- end
1157
-
1158
- private
1159
-
1160
- # If the user is not authorized, just throw the exception.
1161
- def check_authorization
1162
- raise User::NotAuthorized unless current_user.admin?
1163
- end
1164
- end
1165
- ```
1166
-
1167
- WARNING: You shouldn't do `rescue_from Exception` or `rescue_from StandardError` unless you have a particular reason as it will cause serious side-effects (e.g. you won't be able to see exception details and tracebacks during development).
1168
-
1169
- NOTE: 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 [article](http://m.onkey.org/2008/7/20/rescue-from-dispatching) on the subject for more information.
1170
-
1171
- Force HTTPS protocol
1172
- --------------------
1173
-
1174
- Sometime you might want to force a particular controller to only be accessible via an HTTPS protocol for security reasons. You can use the `force_ssl` method in your controller to enforce that:
1175
-
1176
- ```ruby
1177
- class DinnerController
1178
- force_ssl
1179
- end
1180
- ```
1181
-
1182
- Just like the filter, you could also pass `:only` and `:except` to enforce the secure connection only to specific actions:
1183
-
1184
- ```ruby
1185
- class DinnerController
1186
- force_ssl only: :cheeseburger
1187
- # or
1188
- force_ssl except: :cheeseburger
1189
- end
1190
- ```
1191
-
1192
- Please note that if you find yourself adding `force_ssl` to many controllers, you may want to force the whole application to use HTTPS instead. In that case, you can set the `config.force_ssl` in your environment file.