rails 4.1.0 → 5.2.0

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 (284) hide show
  1. checksums.yaml +5 -5
  2. data/README.md +33 -19
  3. metadata +65 -310
  4. data/guides/CHANGELOG.md +0 -13
  5. data/guides/Rakefile +0 -77
  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 -53
  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 -710
  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 -53
  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/code/getting_started/Gemfile +0 -40
  148. data/guides/code/getting_started/Gemfile.lock +0 -126
  149. data/guides/code/getting_started/README.rdoc +0 -28
  150. data/guides/code/getting_started/Rakefile +0 -6
  151. data/guides/code/getting_started/app/assets/javascripts/application.js +0 -15
  152. data/guides/code/getting_started/app/assets/javascripts/comments.js.coffee +0 -3
  153. data/guides/code/getting_started/app/assets/javascripts/posts.js.coffee +0 -3
  154. data/guides/code/getting_started/app/assets/javascripts/welcome.js.coffee +0 -3
  155. data/guides/code/getting_started/app/assets/stylesheets/application.css +0 -13
  156. data/guides/code/getting_started/app/assets/stylesheets/comments.css.scss +0 -3
  157. data/guides/code/getting_started/app/assets/stylesheets/posts.css.scss +0 -3
  158. data/guides/code/getting_started/app/assets/stylesheets/welcome.css.scss +0 -3
  159. data/guides/code/getting_started/app/controllers/application_controller.rb +0 -5
  160. data/guides/code/getting_started/app/controllers/comments_controller.rb +0 -23
  161. data/guides/code/getting_started/app/controllers/posts_controller.rb +0 -53
  162. data/guides/code/getting_started/app/controllers/welcome_controller.rb +0 -4
  163. data/guides/code/getting_started/app/helpers/application_helper.rb +0 -2
  164. data/guides/code/getting_started/app/helpers/comments_helper.rb +0 -2
  165. data/guides/code/getting_started/app/helpers/posts_helper.rb +0 -2
  166. data/guides/code/getting_started/app/helpers/welcome_helper.rb +0 -2
  167. data/guides/code/getting_started/app/models/comment.rb +0 -3
  168. data/guides/code/getting_started/app/models/post.rb +0 -7
  169. data/guides/code/getting_started/app/views/comments/_comment.html.erb +0 -15
  170. data/guides/code/getting_started/app/views/comments/_form.html.erb +0 -13
  171. data/guides/code/getting_started/app/views/layouts/application.html.erb +0 -14
  172. data/guides/code/getting_started/app/views/posts/_form.html.erb +0 -27
  173. data/guides/code/getting_started/app/views/posts/edit.html.erb +0 -5
  174. data/guides/code/getting_started/app/views/posts/index.html.erb +0 -21
  175. data/guides/code/getting_started/app/views/posts/new.html.erb +0 -5
  176. data/guides/code/getting_started/app/views/posts/show.html.erb +0 -18
  177. data/guides/code/getting_started/app/views/welcome/index.html.erb +0 -4
  178. data/guides/code/getting_started/bin/bundle +0 -4
  179. data/guides/code/getting_started/bin/rails +0 -4
  180. data/guides/code/getting_started/bin/rake +0 -4
  181. data/guides/code/getting_started/config.ru +0 -4
  182. data/guides/code/getting_started/config/application.rb +0 -18
  183. data/guides/code/getting_started/config/boot.rb +0 -4
  184. data/guides/code/getting_started/config/database.yml +0 -25
  185. data/guides/code/getting_started/config/environment.rb +0 -5
  186. data/guides/code/getting_started/config/environments/development.rb +0 -30
  187. data/guides/code/getting_started/config/environments/production.rb +0 -80
  188. data/guides/code/getting_started/config/environments/test.rb +0 -36
  189. data/guides/code/getting_started/config/initializers/backtrace_silencers.rb +0 -7
  190. data/guides/code/getting_started/config/initializers/filter_parameter_logging.rb +0 -4
  191. data/guides/code/getting_started/config/initializers/inflections.rb +0 -16
  192. data/guides/code/getting_started/config/initializers/locale.rb +0 -9
  193. data/guides/code/getting_started/config/initializers/mime_types.rb +0 -5
  194. data/guides/code/getting_started/config/initializers/secret_token.rb +0 -12
  195. data/guides/code/getting_started/config/initializers/session_store.rb +0 -3
  196. data/guides/code/getting_started/config/initializers/wrap_parameters.rb +0 -14
  197. data/guides/code/getting_started/config/locales/en.yml +0 -23
  198. data/guides/code/getting_started/config/routes.rb +0 -7
  199. data/guides/code/getting_started/db/migrate/20130122042648_create_posts.rb +0 -10
  200. data/guides/code/getting_started/db/migrate/20130122045842_create_comments.rb +0 -11
  201. data/guides/code/getting_started/db/schema.rb +0 -33
  202. data/guides/code/getting_started/db/seeds.rb +0 -7
  203. data/guides/code/getting_started/public/404.html +0 -60
  204. data/guides/code/getting_started/public/422.html +0 -60
  205. data/guides/code/getting_started/public/500.html +0 -59
  206. data/guides/code/getting_started/public/favicon.ico +0 -0
  207. data/guides/code/getting_started/public/robots.txt +0 -5
  208. data/guides/code/getting_started/test/controllers/comments_controller_test.rb +0 -7
  209. data/guides/code/getting_started/test/controllers/posts_controller_test.rb +0 -7
  210. data/guides/code/getting_started/test/controllers/welcome_controller_test.rb +0 -9
  211. data/guides/code/getting_started/test/fixtures/comments.yml +0 -11
  212. data/guides/code/getting_started/test/fixtures/posts.yml +0 -9
  213. data/guides/code/getting_started/test/helpers/comments_helper_test.rb +0 -4
  214. data/guides/code/getting_started/test/helpers/posts_helper_test.rb +0 -4
  215. data/guides/code/getting_started/test/helpers/welcome_helper_test.rb +0 -4
  216. data/guides/code/getting_started/test/models/comment_test.rb +0 -7
  217. data/guides/code/getting_started/test/models/post_test.rb +0 -7
  218. data/guides/code/getting_started/test/test_helper.rb +0 -15
  219. data/guides/rails_guides.rb +0 -63
  220. data/guides/rails_guides/generator.rb +0 -248
  221. data/guides/rails_guides/helpers.rb +0 -53
  222. data/guides/rails_guides/indexer.rb +0 -68
  223. data/guides/rails_guides/kindle.rb +0 -119
  224. data/guides/rails_guides/levenshtein.rb +0 -31
  225. data/guides/rails_guides/markdown.rb +0 -163
  226. data/guides/rails_guides/markdown/renderer.rb +0 -82
  227. data/guides/source/2_2_release_notes.md +0 -435
  228. data/guides/source/2_3_release_notes.md +0 -621
  229. data/guides/source/3_0_release_notes.md +0 -611
  230. data/guides/source/3_1_release_notes.md +0 -556
  231. data/guides/source/3_2_release_notes.md +0 -565
  232. data/guides/source/4_0_release_notes.md +0 -276
  233. data/guides/source/4_1_release_notes.md +0 -731
  234. data/guides/source/_license.html.erb +0 -2
  235. data/guides/source/_welcome.html.erb +0 -22
  236. data/guides/source/action_controller_overview.md +0 -1175
  237. data/guides/source/action_mailer_basics.md +0 -689
  238. data/guides/source/action_view_overview.md +0 -1610
  239. data/guides/source/active_model_basics.md +0 -200
  240. data/guides/source/active_record_basics.md +0 -373
  241. data/guides/source/active_record_callbacks.md +0 -410
  242. data/guides/source/active_record_querying.md +0 -1771
  243. data/guides/source/active_record_validations.md +0 -1169
  244. data/guides/source/active_support_core_extensions.md +0 -3864
  245. data/guides/source/active_support_instrumentation.md +0 -496
  246. data/guides/source/api_documentation_guidelines.md +0 -281
  247. data/guides/source/asset_pipeline.md +0 -1163
  248. data/guides/source/association_basics.md +0 -2229
  249. data/guides/source/caching_with_rails.md +0 -354
  250. data/guides/source/command_line.md +0 -603
  251. data/guides/source/configuring.md +0 -942
  252. data/guides/source/contributing_to_ruby_on_rails.md +0 -544
  253. data/guides/source/credits.html.erb +0 -80
  254. data/guides/source/debugging_rails_applications.md +0 -707
  255. data/guides/source/development_dependencies_install.md +0 -278
  256. data/guides/source/documents.yaml +0 -194
  257. data/guides/source/engines.md +0 -1391
  258. data/guides/source/form_helpers.md +0 -1001
  259. data/guides/source/generators.md +0 -663
  260. data/guides/source/getting_started.md +0 -1947
  261. data/guides/source/i18n.md +0 -1043
  262. data/guides/source/index.html.erb +0 -27
  263. data/guides/source/initialization.md +0 -657
  264. data/guides/source/kindle/copyright.html.erb +0 -1
  265. data/guides/source/kindle/layout.html.erb +0 -27
  266. data/guides/source/kindle/rails_guides.opf.erb +0 -52
  267. data/guides/source/kindle/toc.html.erb +0 -24
  268. data/guides/source/kindle/toc.ncx.erb +0 -64
  269. data/guides/source/kindle/welcome.html.erb +0 -5
  270. data/guides/source/layout.html.erb +0 -146
  271. data/guides/source/layouts_and_rendering.md +0 -1226
  272. data/guides/source/maintenance_policy.md +0 -56
  273. data/guides/source/migrations.md +0 -1108
  274. data/guides/source/nested_model_forms.md +0 -225
  275. data/guides/source/plugins.md +0 -444
  276. data/guides/source/rails_application_templates.md +0 -248
  277. data/guides/source/rails_on_rack.md +0 -333
  278. data/guides/source/routing.md +0 -1115
  279. data/guides/source/ruby_on_rails_guides_guidelines.md +0 -128
  280. data/guides/source/security.md +0 -1018
  281. data/guides/source/testing.md +0 -1057
  282. data/guides/source/upgrading_ruby_on_rails.md +0 -890
  283. data/guides/source/working_with_javascript_in_rails.md +0 -405
  284. data/guides/w3c_validator.rb +0 -95
@@ -1,2 +0,0 @@
1
- <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>
2
- <p>"Rails", "Ruby on Rails", and the Rails logo are trademarks of David Heinemeier Hansson. All rights reserved.</p>
@@ -1,22 +0,0 @@
1
- <h2>Ruby on Rails Guides (<%= @edge ? @version[0, 7] : @version %>)</h2>
2
-
3
- <% if @edge %>
4
- <p>
5
- These are <b>Edge Guides</b>, based on the current <a href="https://github.com/rails/rails/tree/<%= @version %>">master</a> branch.
6
- </p>
7
- <p>
8
- If you are looking for the ones for the stable version, please check
9
- <a href="http://guides.rubyonrails.org">http://guides.rubyonrails.org</a> instead.
10
- </p>
11
- <% else %>
12
- <p>
13
- These are the new guides for Rails 4.0 based on <a href="https://github.com/rails/rails/tree/<%= @version %>"><%= @version %></a>.
14
- These guides are designed to make you immediately productive with Rails, and to help you understand how all of the pieces fit together.
15
- </p>
16
- <% end %>
17
- <p>
18
- The guides for Rails 3.2.x are available at <a href="http://guides.rubyonrails.org/v3.2.17/">http://guides.rubyonrails.org/v3.2.17/</a>.
19
- </p>
20
- <p>
21
- The guides for Rails 2.3.x are available at <a href="http://guides.rubyonrails.org/v2.3.11/">http://guides.rubyonrails.org/v2.3.11/</a>.
22
- </p>
@@ -1,1175 +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 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 subhash 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
- # YourApp::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
- YourApp::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
- YourApp::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/initializers/secret_token.rb`
385
-
386
- ```ruby
387
- # Be sure to restart your server when you modify this file.
388
-
389
- # Your secret key for verifying the integrity of signed cookies.
390
- # If you change this key, all old signed cookies will become invalid!
391
- # Make sure the secret is at least 30 characters and all random,
392
- # no regular words or you'll be exposed to dictionary attacks.
393
- YourApp::Application.config.secret_key_base = '49d3f3de9ed86c74b94ad6bd0...'
394
- ```
395
-
396
- NOTE: Changing the secret when using the `CookieStore` will invalidate all existing sessions.
397
-
398
- ### Accessing the Session
399
-
400
- In your controller you can access the session through the `session` instance method.
401
-
402
- 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.
403
-
404
- Session values are stored using key/value pairs like a hash:
405
-
406
- ```ruby
407
- class ApplicationController < ActionController::Base
408
-
409
- private
410
-
411
- # Finds the User with the ID stored in the session with the key
412
- # :current_user_id This is a common way to handle user login in
413
- # a Rails application; logging in sets the session value and
414
- # logging out removes it.
415
- def current_user
416
- @_current_user ||= session[:current_user_id] &&
417
- User.find_by(id: session[:current_user_id])
418
- end
419
- end
420
- ```
421
-
422
- To store something in the session, just assign it to the key like a hash:
423
-
424
- ```ruby
425
- class LoginsController < ApplicationController
426
- # "Create" a login, aka "log the user in"
427
- def create
428
- if user = User.authenticate(params[:username], params[:password])
429
- # Save the user ID in the session so it can be used in
430
- # subsequent requests
431
- session[:current_user_id] = user.id
432
- redirect_to root_url
433
- end
434
- end
435
- end
436
- ```
437
-
438
- To remove something from the session, assign that key to be `nil`:
439
-
440
- ```ruby
441
- class LoginsController < ApplicationController
442
- # "Delete" a login, aka "log the user out"
443
- def destroy
444
- # Remove the user id from the session
445
- @_current_user = session[:current_user_id] = nil
446
- redirect_to root_url
447
- end
448
- end
449
- ```
450
-
451
- To reset the entire session, use `reset_session`.
452
-
453
- ### The Flash
454
-
455
- 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.
456
-
457
- 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).
458
-
459
- 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:
460
-
461
- ```ruby
462
- class LoginsController < ApplicationController
463
- def destroy
464
- session[:current_user_id] = nil
465
- flash[:notice] = "You have successfully logged out."
466
- redirect_to root_url
467
- end
468
- end
469
- ```
470
-
471
- 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`:
472
-
473
- ```ruby
474
- redirect_to root_url, notice: "You have successfully logged out."
475
- redirect_to root_url, alert: "You're stuck here!"
476
- redirect_to root_url, flash: { referral_code: 1234 }
477
- ```
478
-
479
- 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:
480
-
481
- ```erb
482
- <html>
483
- <!-- <head/> -->
484
- <body>
485
- <% flash.each do |name, msg| -%>
486
- <%= content_tag :div, msg, class: name %>
487
- <% end -%>
488
-
489
- <!-- more content -->
490
- </body>
491
- </html>
492
- ```
493
-
494
- This way, if an action sets a notice or an alert message, the layout will display it automatically.
495
-
496
- You can pass anything that the session can store; you're not limited to notices and alerts:
497
-
498
- ```erb
499
- <% if flash[:just_signed_up] %>
500
- <p class="welcome">Welcome to our site!</p>
501
- <% end %>
502
- ```
503
-
504
- If you want a flash value to be carried over to another request, use the `keep` method:
505
-
506
- ```ruby
507
- class MainController < ApplicationController
508
- # Let's say this action corresponds to root_url, but you want
509
- # all requests here to be redirected to UsersController#index.
510
- # If an action sets the flash and redirects here, the values
511
- # would normally be lost when another redirect happens, but you
512
- # can use 'keep' to make it persist for another request.
513
- def index
514
- # Will persist all flash values.
515
- flash.keep
516
-
517
- # You can also use a key to keep only some kind of value.
518
- # flash.keep(:notice)
519
- redirect_to users_url
520
- end
521
- end
522
- ```
523
-
524
- #### `flash.now`
525
-
526
- 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`:
527
-
528
- ```ruby
529
- class ClientsController < ApplicationController
530
- def create
531
- @client = Client.new(params[:client])
532
- if @client.save
533
- # ...
534
- else
535
- flash.now[:error] = "Could not save client"
536
- render action: "new"
537
- end
538
- end
539
- end
540
- ```
541
-
542
- Cookies
543
- -------
544
-
545
- 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:
546
-
547
- ```ruby
548
- class CommentsController < ApplicationController
549
- def new
550
- # Auto-fill the commenter's name if it has been stored in a cookie
551
- @comment = Comment.new(author: cookies[:commenter_name])
552
- end
553
-
554
- def create
555
- @comment = Comment.new(params[:comment])
556
- if @comment.save
557
- flash[:notice] = "Thanks for your comment!"
558
- if params[:remember_name]
559
- # Remember the commenter's name.
560
- cookies[:commenter_name] = @comment.author
561
- else
562
- # Delete cookie for the commenter's name cookie, if any.
563
- cookies.delete(:commenter_name)
564
- end
565
- redirect_to @comment.article
566
- else
567
- render action: "new"
568
- end
569
- end
570
- end
571
- ```
572
-
573
- Note that while for session values you set the key to `nil`, to delete a cookie value you should use `cookies.delete(:key)`.
574
-
575
- Rails also provides a signed cookie jar and an encrypted cookie jar for storing
576
- sensitive data. The signed cookie jar appends a cryptographic signature on the
577
- cookie values to protect their integrity. The encrypted cookie jar encrypts the
578
- values in addition to signing them, so that they cannot be read by the end user.
579
- Refer to the [API documentation](http://api.rubyonrails.org/classes/ActionDispatch/Cookies.html)
580
- for more details.
581
-
582
- These special cookie jars use a serializer to serialize the assigned values into
583
- strings and deserializes them into Ruby objects on read.
584
-
585
- You can specify what serializer to use:
586
-
587
- ```ruby
588
- Rails.application.config.action_dispatch.cookies_serializer = :json
589
- ```
590
-
591
- The default serializer for new applications is `:json`. For compatibility with
592
- old applications with existing cookies, `:marshal` is used when `serializer`
593
- option is not specified.
594
-
595
- You may also set this option to `:hybrid`, in which case Rails would transparently
596
- deserialize existing (`Marshal`-serialized) cookies on read and re-write them in
597
- the `JSON` format. This is useful for migrating existing applications to the
598
- `:json` serializer.
599
-
600
- It is also possible to pass a custom serializer that responds to `load` and
601
- `dump`:
602
-
603
- ```ruby
604
- Rails.application.config.action_dispatch.cookies_serializer = MyCustomSerializer
605
- ```
606
-
607
- When using the `:json` or `:hybrid` serializer, you should beware that not all
608
- Ruby objects can be serialized as JSON. For example, `Date` and `Time` objects
609
- will be serialized as strings, and `Hash`es will have their keys stringified.
610
-
611
- ```ruby
612
- class CookiesController < ApplicationController
613
- def set_cookie
614
- cookies.encrypted[:expiration_date] = Date.tomorrow # => Thu, 20 Mar 2014
615
- redirect_to action: 'read_cookie'
616
- end
617
-
618
- def read_cookie
619
- cookies.encrypted[:expiration_date] # => "2014-03-20"
620
- end
621
- end
622
- ```
623
-
624
- It's advisable that you only store simple data (strings and numbers) in cookies.
625
- If you have to store complex objects, you would need to handle the conversion
626
- manually when reading the values on subsequent requests.
627
-
628
- If you use the cookie session store, this would apply to the `session` and
629
- `flash` hash as well.
630
-
631
- Rendering XML and JSON data
632
- ---------------------------
633
-
634
- 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:
635
-
636
- ```ruby
637
- class UsersController < ApplicationController
638
- def index
639
- @users = User.all
640
- respond_to do |format|
641
- format.html # index.html.erb
642
- format.xml { render xml: @users}
643
- format.json { render json: @users}
644
- end
645
- end
646
- end
647
- ```
648
-
649
- 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.
650
-
651
- Filters
652
- -------
653
-
654
- Filters are methods that are run before, after or "around" a controller action.
655
-
656
- Filters are inherited, so if you set a filter on `ApplicationController`, it will be run on every controller in your application.
657
-
658
- "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:
659
-
660
- ```ruby
661
- class ApplicationController < ActionController::Base
662
- before_action :require_login
663
-
664
- private
665
-
666
- def require_login
667
- unless logged_in?
668
- flash[:error] = "You must be logged in to access this section"
669
- redirect_to new_login_url # halts request cycle
670
- end
671
- end
672
- end
673
- ```
674
-
675
- 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.
676
-
677
- 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`:
678
-
679
- ```ruby
680
- class LoginsController < ApplicationController
681
- skip_before_action :require_login, only: [:new, :create]
682
- end
683
- ```
684
-
685
- 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.
686
-
687
- ### After Filters and Around Filters
688
-
689
- In addition to "before" filters, you can also run filters after an action has been executed, or both before and after.
690
-
691
- "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.
692
-
693
- "Around" filters are responsible for running their associated actions by yielding, similar to how Rack middlewares work.
694
-
695
- 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:
696
-
697
- ```ruby
698
- class ChangesController < ApplicationController
699
- around_action :wrap_in_transaction, only: :show
700
-
701
- private
702
-
703
- def wrap_in_transaction
704
- ActiveRecord::Base.transaction do
705
- begin
706
- yield
707
- ensure
708
- raise ActiveRecord::Rollback
709
- end
710
- end
711
- end
712
- end
713
- ```
714
-
715
- 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.
716
-
717
- You can choose not to yield and build the response yourself, in which case the action will not be run.
718
-
719
- ### Other Ways to Use Filters
720
-
721
- 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.
722
-
723
- 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:
724
-
725
- ```ruby
726
- class ApplicationController < ActionController::Base
727
- before_action do |controller|
728
- unless controller.send(:logged_in?)
729
- flash[:error] = "You must be logged in to access this section"
730
- redirect_to new_login_url
731
- end
732
- end
733
- end
734
- ```
735
-
736
- 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.
737
-
738
- 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:
739
-
740
- ```ruby
741
- class ApplicationController < ActionController::Base
742
- before_action LoginFilter
743
- end
744
-
745
- class LoginFilter
746
- def self.before(controller)
747
- unless controller.send(:logged_in?)
748
- controller.flash[:error] = "You must be logged in to access this section"
749
- controller.redirect_to controller.new_login_url
750
- end
751
- end
752
- end
753
- ```
754
-
755
- 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.
756
-
757
- Request Forgery Protection
758
- --------------------------
759
-
760
- 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.
761
-
762
- 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.
763
-
764
- 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.
765
-
766
- If you generate a form like this:
767
-
768
- ```erb
769
- <%= form_for @user do |f| %>
770
- <%= f.text_field :username %>
771
- <%= f.text_field :password %>
772
- <% end %>
773
- ```
774
-
775
- You will see how the token gets added as a hidden field:
776
-
777
- ```html
778
- <form accept-charset="UTF-8" action="/users/1" method="post">
779
- <input type="hidden"
780
- value="67250ab105eb5ad10851c00a5621854a23af5489"
781
- name="authenticity_token"/>
782
- <!-- fields -->
783
- </form>
784
- ```
785
-
786
- 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`:
787
-
788
- 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.
789
-
790
- 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.
791
-
792
- The Request and Response Objects
793
- --------------------------------
794
-
795
- 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.
796
-
797
- ### The `request` Object
798
-
799
- 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:
800
-
801
- | Property of `request` | Purpose |
802
- | ----------------------------------------- | -------------------------------------------------------------------------------- |
803
- | host | The hostname used for this request. |
804
- | domain(n=2) | The hostname's first `n` segments, starting from the right (the TLD). |
805
- | format | The content type requested by the client. |
806
- | method | The HTTP method used for the request. |
807
- | get?, post?, patch?, put?, delete?, head? | Returns true if the HTTP method is GET/POST/PATCH/PUT/DELETE/HEAD. |
808
- | headers | Returns a hash containing the headers associated with the request. |
809
- | port | The port number (integer) used for the request. |
810
- | protocol | Returns a string containing the protocol used plus "://", for example "http://". |
811
- | query_string | The query string part of the URL, i.e., everything after "?". |
812
- | remote_ip | The IP address of the client. |
813
- | url | The entire URL used for the request. |
814
-
815
- #### `path_parameters`, `query_parameters`, and `request_parameters`
816
-
817
- 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.
818
-
819
- ### The `response` Object
820
-
821
- 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.
822
-
823
- | Property of `response` | Purpose |
824
- | ---------------------- | --------------------------------------------------------------------------------------------------- |
825
- | body | This is the string of data being sent back to the client. This is most often HTML. |
826
- | status | The HTTP status code for the response, like 200 for a successful request or 404 for file not found. |
827
- | location | The URL the client is being redirected to, if any. |
828
- | content_type | The content type of the response. |
829
- | charset | The character set being used for the response. Default is "utf-8". |
830
- | headers | Headers used for the response. |
831
-
832
- #### Setting Custom Headers
833
-
834
- 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:
835
-
836
- ```ruby
837
- response.headers["Content-Type"] = "application/pdf"
838
- ```
839
-
840
- Note: in the above case it would make more sense to use the `content_type` setter directly.
841
-
842
- HTTP Authentications
843
- --------------------
844
-
845
- Rails comes with two built-in HTTP authentication mechanisms:
846
-
847
- * Basic Authentication
848
- * Digest Authentication
849
-
850
- ### HTTP Basic Authentication
851
-
852
- 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`.
853
-
854
- ```ruby
855
- class AdminsController < ApplicationController
856
- http_basic_authenticate_with name: "humbaba", password: "5baa61e4"
857
- end
858
- ```
859
-
860
- 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.
861
-
862
- ### HTTP Digest Authentication
863
-
864
- 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`.
865
-
866
- ```ruby
867
- class AdminsController < ApplicationController
868
- USERS = { "lifo" => "world" }
869
-
870
- before_action :authenticate
871
-
872
- private
873
-
874
- def authenticate
875
- authenticate_or_request_with_http_digest do |username|
876
- USERS[username]
877
- end
878
- end
879
- end
880
- ```
881
-
882
- 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.
883
-
884
- Streaming and File Downloads
885
- ----------------------------
886
-
887
- 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.
888
-
889
- To stream data to the client, use `send_data`:
890
-
891
- ```ruby
892
- require "prawn"
893
- class ClientsController < ApplicationController
894
- # Generates a PDF document with information on the client and
895
- # returns it. The user will get the PDF as a file download.
896
- def download_pdf
897
- client = Client.find(params[:id])
898
- send_data generate_pdf(client),
899
- filename: "#{client.name}.pdf",
900
- type: "application/pdf"
901
- end
902
-
903
- private
904
-
905
- def generate_pdf(client)
906
- Prawn::Document.new do
907
- text client.name, align: :center
908
- text "Address: #{client.address}"
909
- text "Email: #{client.email}"
910
- end.render
911
- end
912
- end
913
- ```
914
-
915
- 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".
916
-
917
- ### Sending Files
918
-
919
- If you want to send a file that already exists on disk, use the `send_file` method.
920
-
921
- ```ruby
922
- class ClientsController < ApplicationController
923
- # Stream a file that has already been generated and stored on disk.
924
- def download_pdf
925
- client = Client.find(params[:id])
926
- send_file("#{Rails.root}/files/clients/#{client.id}.pdf",
927
- filename: "#{client.name}.pdf",
928
- type: "application/pdf")
929
- end
930
- end
931
- ```
932
-
933
- 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.
934
-
935
- 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.
936
-
937
- 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.
938
-
939
- 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.
940
-
941
- ### RESTful Downloads
942
-
943
- 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:
944
-
945
- ```ruby
946
- class ClientsController < ApplicationController
947
- # The user can request to receive this resource as HTML or PDF.
948
- def show
949
- @client = Client.find(params[:id])
950
-
951
- respond_to do |format|
952
- format.html
953
- format.pdf { render pdf: generate_pdf(@client) }
954
- end
955
- end
956
- end
957
- ```
958
-
959
- 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`:
960
-
961
- ```ruby
962
- Mime::Type.register "application/pdf", :pdf
963
- ```
964
-
965
- NOTE: Configuration files are not reloaded on each request, so you have to restart the server in order for their changes to take effect.
966
-
967
- Now the user can request to get a PDF version of a client just by adding ".pdf" to the URL:
968
-
969
- ```bash
970
- GET /clients/1.pdf
971
- ```
972
-
973
- ### Live Streaming of Arbitrary Data
974
-
975
- Rails allows you to stream more than just files. In fact, you can stream anything
976
- you would like in a response object. The `ActionController::Live` module allows
977
- you to create a persistent connection with a browser. Using this module, you will
978
- be able to send arbitrary data to the browser at specific points in time.
979
-
980
- #### Incorporating Live Streaming
981
-
982
- Including `ActionController::Live` inside of your controller class will provide
983
- all actions inside of the controller the ability to stream data. You can mix in
984
- the module like so:
985
-
986
- ```ruby
987
- class MyController < ActionController::Base
988
- include ActionController::Live
989
-
990
- def stream
991
- response.headers['Content-Type'] = 'text/event-stream'
992
- 100.times {
993
- response.stream.write "hello world\n"
994
- sleep 1
995
- }
996
- ensure
997
- response.stream.close
998
- end
999
- end
1000
- ```
1001
-
1002
- The above code will keep a persistent connection with the browser and send 100
1003
- messages of `"hello world\n"`, each one second apart.
1004
-
1005
- There are a couple of things to notice in the above example. We need to make
1006
- sure to close the response stream. Forgetting to close the stream will leave
1007
- the socket open forever. We also have to set the content type to `text/event-stream`
1008
- before we write to the response stream. This is because headers cannot be written
1009
- after the response has been committed (when `response.committed` returns a truthy
1010
- value), which occurs when you `write` or `commit` the response stream.
1011
-
1012
- #### Example Usage
1013
-
1014
- Let's suppose that you were making a Karaoke machine and a user wants to get the
1015
- lyrics for a particular song. Each `Song` has a particular number of lines and
1016
- each line takes time `num_beats` to finish singing.
1017
-
1018
- If we wanted to return the lyrics in Karaoke fashion (only sending the line when
1019
- the singer has finished the previous line), then we could use `ActionController::Live`
1020
- as follows:
1021
-
1022
- ```ruby
1023
- class LyricsController < ActionController::Base
1024
- include ActionController::Live
1025
-
1026
- def show
1027
- response.headers['Content-Type'] = 'text/event-stream'
1028
- song = Song.find(params[:id])
1029
-
1030
- song.each do |line|
1031
- response.stream.write line.lyrics
1032
- sleep line.num_beats
1033
- end
1034
- ensure
1035
- response.stream.close
1036
- end
1037
- end
1038
- ```
1039
-
1040
- The above code sends the next line only after the singer has completed the previous
1041
- line.
1042
-
1043
- #### Streaming Considerations
1044
-
1045
- Streaming arbitrary data is an extremely powerful tool. As shown in the previous
1046
- examples, you can choose when and what to send across a response stream. However,
1047
- you should also note the following things:
1048
-
1049
- * Each response stream creates a new thread and copies over the thread local
1050
- variables from the original thread. Having too many thread local variables can
1051
- negatively impact performance. Similarly, a large number of threads can also
1052
- hinder performance.
1053
- * Failing to close the response stream will leave the corresponding socket open
1054
- forever. Make sure to call `close` whenever you are using a response stream.
1055
- * WEBrick servers buffer all responses, and so including `ActionController::Live`
1056
- will not work. You must use a web server which does not automatically buffer
1057
- responses.
1058
-
1059
- Log Filtering
1060
- -------------
1061
-
1062
- 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.
1063
-
1064
- ### Parameters Filtering
1065
-
1066
- You can filter certain 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.
1067
-
1068
- ```ruby
1069
- config.filter_parameters << :password
1070
- ```
1071
-
1072
- ### Redirects Filtering
1073
-
1074
- Sometimes it's desirable to filter out from log files some sensible locations your application is redirecting to.
1075
- You can do that by using the `config.filter_redirect` configuration option:
1076
-
1077
- ```ruby
1078
- config.filter_redirect << 's3.amazonaws.com'
1079
- ```
1080
-
1081
- You can set it to a String, a Regexp, or an array of both.
1082
-
1083
- ```ruby
1084
- config.filter_redirect.concat ['s3.amazonaws.com', /private_path/]
1085
- ```
1086
-
1087
- Matching URLs will be marked as '[FILTERED]'.
1088
-
1089
- Rescue
1090
- ------
1091
-
1092
- 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.
1093
-
1094
- 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:
1095
-
1096
- ### The Default 500 and 404 Templates
1097
-
1098
- 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.
1099
-
1100
- ### `rescue_from`
1101
-
1102
- 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.
1103
-
1104
- 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.
1105
-
1106
- Here's how you can use `rescue_from` to intercept all `ActiveRecord::RecordNotFound` errors and do something with them.
1107
-
1108
- ```ruby
1109
- class ApplicationController < ActionController::Base
1110
- rescue_from ActiveRecord::RecordNotFound, with: :record_not_found
1111
-
1112
- private
1113
-
1114
- def record_not_found
1115
- render plain: "404 Not Found", status: 404
1116
- end
1117
- end
1118
- ```
1119
-
1120
- 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:
1121
-
1122
- ```ruby
1123
- class ApplicationController < ActionController::Base
1124
- rescue_from User::NotAuthorized, with: :user_not_authorized
1125
-
1126
- private
1127
-
1128
- def user_not_authorized
1129
- flash[:error] = "You don't have access to this section."
1130
- redirect_to :back
1131
- end
1132
- end
1133
-
1134
- class ClientsController < ApplicationController
1135
- # Check that the user has the right authorization to access clients.
1136
- before_action :check_authorization
1137
-
1138
- # Note how the actions don't have to worry about all the auth stuff.
1139
- def edit
1140
- @client = Client.find(params[:id])
1141
- end
1142
-
1143
- private
1144
-
1145
- # If the user is not authorized, just throw the exception.
1146
- def check_authorization
1147
- raise User::NotAuthorized unless current_user.admin?
1148
- end
1149
- end
1150
- ```
1151
-
1152
- 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.
1153
-
1154
- Force HTTPS protocol
1155
- --------------------
1156
-
1157
- 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:
1158
-
1159
- ```ruby
1160
- class DinnerController
1161
- force_ssl
1162
- end
1163
- ```
1164
-
1165
- Just like the filter, you could also pass `:only` and `:except` to enforce the secure connection only to specific actions:
1166
-
1167
- ```ruby
1168
- class DinnerController
1169
- force_ssl only: :cheeseburger
1170
- # or
1171
- force_ssl except: :cheeseburger
1172
- end
1173
- ```
1174
-
1175
- 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.