rails 3.2.22.5 → 4.0.0.beta1

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 (281) hide show
  1. checksums.yaml +4 -4
  2. data/README.rdoc +77 -0
  3. data/guides/CHANGELOG.md +9 -0
  4. data/guides/Rakefile +77 -0
  5. data/guides/assets/images/belongs_to.png +0 -0
  6. data/guides/assets/images/book_icon.gif +0 -0
  7. data/guides/assets/images/bullet.gif +0 -0
  8. data/guides/assets/images/challenge.png +0 -0
  9. data/guides/assets/images/chapters_icon.gif +0 -0
  10. data/guides/assets/images/check_bullet.gif +0 -0
  11. data/guides/assets/images/credits_pic_blank.gif +0 -0
  12. data/guides/assets/images/csrf.png +0 -0
  13. data/guides/assets/images/edge_badge.png +0 -0
  14. data/guides/assets/images/favicon.ico +0 -0
  15. data/guides/assets/images/feature_tile.gif +0 -0
  16. data/guides/assets/images/footer_tile.gif +0 -0
  17. data/guides/assets/images/fxn.png +0 -0
  18. data/guides/assets/images/getting_started/confirm_dialog.png +0 -0
  19. data/guides/assets/images/getting_started/forbidden_attributes_for_new_post.png +0 -0
  20. data/guides/assets/images/getting_started/form_with_errors.png +0 -0
  21. data/guides/assets/images/getting_started/index_action_with_edit_link.png +0 -0
  22. data/guides/assets/images/getting_started/new_post.png +0 -0
  23. data/guides/assets/images/getting_started/post_with_comments.png +0 -0
  24. data/guides/assets/images/getting_started/routing_error_no_controller.png +0 -0
  25. data/guides/assets/images/getting_started/routing_error_no_route_matches.png +0 -0
  26. data/guides/assets/images/getting_started/show_action_for_posts.png +0 -0
  27. data/guides/assets/images/getting_started/template_is_missing_posts_new.png +0 -0
  28. data/guides/assets/images/getting_started/undefined_method_post_path.png +0 -0
  29. data/guides/assets/images/getting_started/unknown_action_create_for_posts.png +0 -0
  30. data/guides/assets/images/getting_started/unknown_action_new_for_posts.png +0 -0
  31. data/guides/assets/images/grey_bullet.gif +0 -0
  32. data/guides/assets/images/habtm.png +0 -0
  33. data/guides/assets/images/has_many.png +0 -0
  34. data/guides/assets/images/has_many_through.png +0 -0
  35. data/guides/assets/images/has_one.png +0 -0
  36. data/guides/assets/images/has_one_through.png +0 -0
  37. data/guides/assets/images/header_backdrop.png +0 -0
  38. data/guides/assets/images/header_tile.gif +0 -0
  39. data/guides/assets/images/i18n/demo_html_safe.png +0 -0
  40. data/guides/assets/images/i18n/demo_localized_pirate.png +0 -0
  41. data/guides/assets/images/i18n/demo_translated_en.png +0 -0
  42. data/guides/assets/images/i18n/demo_translated_pirate.png +0 -0
  43. data/guides/assets/images/i18n/demo_translation_missing.png +0 -0
  44. data/guides/assets/images/i18n/demo_untranslated.png +0 -0
  45. data/guides/assets/images/icons/README +5 -0
  46. data/guides/assets/images/icons/callouts/1.png +0 -0
  47. data/guides/assets/images/icons/callouts/10.png +0 -0
  48. data/guides/assets/images/icons/callouts/11.png +0 -0
  49. data/guides/assets/images/icons/callouts/12.png +0 -0
  50. data/guides/assets/images/icons/callouts/13.png +0 -0
  51. data/guides/assets/images/icons/callouts/14.png +0 -0
  52. data/guides/assets/images/icons/callouts/15.png +0 -0
  53. data/guides/assets/images/icons/callouts/2.png +0 -0
  54. data/guides/assets/images/icons/callouts/3.png +0 -0
  55. data/guides/assets/images/icons/callouts/4.png +0 -0
  56. data/guides/assets/images/icons/callouts/5.png +0 -0
  57. data/guides/assets/images/icons/callouts/6.png +0 -0
  58. data/guides/assets/images/icons/callouts/7.png +0 -0
  59. data/guides/assets/images/icons/callouts/8.png +0 -0
  60. data/guides/assets/images/icons/callouts/9.png +0 -0
  61. data/guides/assets/images/icons/caution.png +0 -0
  62. data/guides/assets/images/icons/example.png +0 -0
  63. data/guides/assets/images/icons/home.png +0 -0
  64. data/guides/assets/images/icons/important.png +0 -0
  65. data/guides/assets/images/icons/next.png +0 -0
  66. data/guides/assets/images/icons/note.png +0 -0
  67. data/guides/assets/images/icons/prev.png +0 -0
  68. data/guides/assets/images/icons/tip.png +0 -0
  69. data/guides/assets/images/icons/up.png +0 -0
  70. data/guides/assets/images/icons/warning.png +0 -0
  71. data/guides/assets/images/jaimeiniesta.jpg +0 -0
  72. data/guides/assets/images/nav_arrow.gif +0 -0
  73. data/guides/assets/images/oscardelben.jpg +0 -0
  74. data/guides/assets/images/polymorphic.png +0 -0
  75. data/guides/assets/images/radar.png +0 -0
  76. data/guides/assets/images/rails4_features.png +0 -0
  77. data/guides/assets/images/rails_guides_kindle_cover.jpg +0 -0
  78. data/guides/assets/images/rails_guides_logo.gif +0 -0
  79. data/guides/assets/images/rails_logo_remix.gif +0 -0
  80. data/guides/assets/images/rails_welcome.png +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 +57 -0
  90. data/guides/assets/javascripts/jquery.min.js +4 -0
  91. data/guides/assets/javascripts/responsive-tables.js +43 -0
  92. data/guides/assets/javascripts/syntaxhighlighter/shBrushAS3.js +59 -0
  93. data/guides/assets/javascripts/syntaxhighlighter/shBrushAppleScript.js +75 -0
  94. data/guides/assets/javascripts/syntaxhighlighter/shBrushBash.js +59 -0
  95. data/guides/assets/javascripts/syntaxhighlighter/shBrushCSharp.js +65 -0
  96. data/guides/assets/javascripts/syntaxhighlighter/shBrushColdFusion.js +100 -0
  97. data/guides/assets/javascripts/syntaxhighlighter/shBrushCpp.js +97 -0
  98. data/guides/assets/javascripts/syntaxhighlighter/shBrushCss.js +91 -0
  99. data/guides/assets/javascripts/syntaxhighlighter/shBrushDelphi.js +55 -0
  100. data/guides/assets/javascripts/syntaxhighlighter/shBrushDiff.js +41 -0
  101. data/guides/assets/javascripts/syntaxhighlighter/shBrushErlang.js +52 -0
  102. data/guides/assets/javascripts/syntaxhighlighter/shBrushGroovy.js +67 -0
  103. data/guides/assets/javascripts/syntaxhighlighter/shBrushJScript.js +52 -0
  104. data/guides/assets/javascripts/syntaxhighlighter/shBrushJava.js +57 -0
  105. data/guides/assets/javascripts/syntaxhighlighter/shBrushJavaFX.js +58 -0
  106. data/guides/assets/javascripts/syntaxhighlighter/shBrushPerl.js +72 -0
  107. data/guides/assets/javascripts/syntaxhighlighter/shBrushPhp.js +88 -0
  108. data/guides/assets/javascripts/syntaxhighlighter/shBrushPlain.js +33 -0
  109. data/guides/assets/javascripts/syntaxhighlighter/shBrushPowerShell.js +74 -0
  110. data/guides/assets/javascripts/syntaxhighlighter/shBrushPython.js +64 -0
  111. data/guides/assets/javascripts/syntaxhighlighter/shBrushRuby.js +55 -0
  112. data/guides/assets/javascripts/syntaxhighlighter/shBrushSass.js +94 -0
  113. data/guides/assets/javascripts/syntaxhighlighter/shBrushScala.js +51 -0
  114. data/guides/assets/javascripts/syntaxhighlighter/shBrushSql.js +66 -0
  115. data/guides/assets/javascripts/syntaxhighlighter/shBrushVb.js +56 -0
  116. data/guides/assets/javascripts/syntaxhighlighter/shBrushXml.js +69 -0
  117. data/guides/assets/javascripts/syntaxhighlighter/shCore.js +17 -0
  118. data/guides/assets/stylesheets/fixes.css +16 -0
  119. data/guides/assets/stylesheets/kindle.css +11 -0
  120. data/guides/assets/stylesheets/main.css +709 -0
  121. data/guides/assets/stylesheets/print.css +52 -0
  122. data/guides/assets/stylesheets/reset.css +43 -0
  123. data/guides/assets/stylesheets/responsive-tables.css +50 -0
  124. data/guides/assets/stylesheets/style.css +13 -0
  125. data/guides/assets/stylesheets/syntaxhighlighter/shCore.css +226 -0
  126. data/guides/assets/stylesheets/syntaxhighlighter/shCoreDefault.css +328 -0
  127. data/guides/assets/stylesheets/syntaxhighlighter/shCoreDjango.css +331 -0
  128. data/guides/assets/stylesheets/syntaxhighlighter/shCoreEclipse.css +339 -0
  129. data/guides/assets/stylesheets/syntaxhighlighter/shCoreEmacs.css +324 -0
  130. data/guides/assets/stylesheets/syntaxhighlighter/shCoreFadeToGrey.css +328 -0
  131. data/guides/assets/stylesheets/syntaxhighlighter/shCoreMDUltra.css +324 -0
  132. data/guides/assets/stylesheets/syntaxhighlighter/shCoreMidnight.css +324 -0
  133. data/guides/assets/stylesheets/syntaxhighlighter/shCoreRDark.css +324 -0
  134. data/guides/assets/stylesheets/syntaxhighlighter/shThemeDefault.css +117 -0
  135. data/guides/assets/stylesheets/syntaxhighlighter/shThemeDjango.css +120 -0
  136. data/guides/assets/stylesheets/syntaxhighlighter/shThemeEclipse.css +128 -0
  137. data/guides/assets/stylesheets/syntaxhighlighter/shThemeEmacs.css +113 -0
  138. data/guides/assets/stylesheets/syntaxhighlighter/shThemeFadeToGrey.css +117 -0
  139. data/guides/assets/stylesheets/syntaxhighlighter/shThemeMDUltra.css +113 -0
  140. data/guides/assets/stylesheets/syntaxhighlighter/shThemeMidnight.css +113 -0
  141. data/guides/assets/stylesheets/syntaxhighlighter/shThemeRDark.css +113 -0
  142. data/guides/assets/stylesheets/syntaxhighlighter/shThemeRailsGuides.css +116 -0
  143. data/guides/code/getting_started/Gemfile +38 -0
  144. data/guides/code/getting_started/Gemfile.lock +150 -0
  145. data/guides/code/getting_started/README.rdoc +28 -0
  146. data/guides/code/getting_started/Rakefile +6 -0
  147. data/guides/code/getting_started/app/assets/images/rails.png +0 -0
  148. data/guides/code/getting_started/app/assets/javascripts/application.js +16 -0
  149. data/guides/code/getting_started/app/assets/javascripts/comments.js.coffee +3 -0
  150. data/guides/code/getting_started/app/assets/javascripts/posts.js.coffee +3 -0
  151. data/guides/code/getting_started/app/assets/javascripts/welcome.js.coffee +3 -0
  152. data/guides/code/getting_started/app/assets/stylesheets/application.css +13 -0
  153. data/guides/code/getting_started/app/assets/stylesheets/comments.css.scss +3 -0
  154. data/guides/code/getting_started/app/assets/stylesheets/posts.css.scss +3 -0
  155. data/guides/code/getting_started/app/assets/stylesheets/welcome.css.scss +3 -0
  156. data/guides/code/getting_started/app/controllers/application_controller.rb +5 -0
  157. data/guides/code/getting_started/app/controllers/comments_controller.rb +17 -0
  158. data/guides/code/getting_started/app/controllers/posts_controller.rb +47 -0
  159. data/guides/code/getting_started/app/controllers/welcome_controller.rb +4 -0
  160. data/guides/code/getting_started/app/helpers/application_helper.rb +2 -0
  161. data/guides/code/getting_started/app/helpers/comments_helper.rb +2 -0
  162. data/guides/code/getting_started/app/helpers/posts_helper.rb +2 -0
  163. data/guides/code/getting_started/app/helpers/welcome_helper.rb +2 -0
  164. data/guides/code/getting_started/app/models/comment.rb +3 -0
  165. data/guides/code/getting_started/app/models/post.rb +7 -0
  166. data/guides/code/getting_started/app/views/comments/_comment.html.erb +15 -0
  167. data/guides/code/getting_started/app/views/comments/_form.html.erb +13 -0
  168. data/guides/code/getting_started/app/views/layouts/application.html.erb +14 -0
  169. data/guides/code/getting_started/app/views/posts/_form.html.erb +27 -0
  170. data/guides/code/getting_started/app/views/posts/edit.html.erb +5 -0
  171. data/guides/code/getting_started/app/views/posts/index.html.erb +21 -0
  172. data/guides/code/getting_started/app/views/posts/new.html.erb +5 -0
  173. data/guides/code/getting_started/app/views/posts/show.html.erb +18 -0
  174. data/guides/code/getting_started/app/views/welcome/index.html.erb +3 -0
  175. data/guides/code/getting_started/bin/bundle +4 -0
  176. data/guides/code/getting_started/bin/rails +4 -0
  177. data/guides/code/getting_started/bin/rake +4 -0
  178. data/guides/code/getting_started/config.ru +4 -0
  179. data/guides/code/getting_started/config/application.rb +17 -0
  180. data/guides/code/getting_started/config/boot.rb +4 -0
  181. data/guides/code/getting_started/config/database.yml +25 -0
  182. data/guides/code/getting_started/config/environment.rb +5 -0
  183. data/guides/code/getting_started/config/environments/development.rb +30 -0
  184. data/guides/code/getting_started/config/environments/production.rb +80 -0
  185. data/guides/code/getting_started/config/environments/test.rb +36 -0
  186. data/guides/code/getting_started/config/initializers/backtrace_silencers.rb +7 -0
  187. data/guides/code/getting_started/config/initializers/filter_parameter_logging.rb +4 -0
  188. data/guides/code/getting_started/config/initializers/inflections.rb +16 -0
  189. data/guides/code/getting_started/config/initializers/locale.rb +9 -0
  190. data/guides/code/getting_started/config/initializers/mime_types.rb +5 -0
  191. data/guides/code/getting_started/config/initializers/secret_token.rb +12 -0
  192. data/guides/code/getting_started/config/initializers/session_store.rb +3 -0
  193. data/guides/code/getting_started/config/initializers/wrap_parameters.rb +14 -0
  194. data/guides/code/getting_started/config/locales/en.yml +23 -0
  195. data/guides/code/getting_started/config/routes.rb +7 -0
  196. data/guides/code/getting_started/db/migrate/20130122042648_create_posts.rb +10 -0
  197. data/guides/code/getting_started/db/migrate/20130122045842_create_comments.rb +11 -0
  198. data/guides/code/getting_started/db/schema.rb +33 -0
  199. data/guides/code/getting_started/db/seeds.rb +7 -0
  200. data/guides/code/getting_started/public/404.html +27 -0
  201. data/guides/code/getting_started/public/422.html +26 -0
  202. data/guides/code/getting_started/public/500.html +26 -0
  203. data/guides/code/getting_started/public/favicon.ico +0 -0
  204. data/guides/code/getting_started/public/robots.txt +5 -0
  205. data/guides/code/getting_started/test/controllers/comments_controller_test.rb +7 -0
  206. data/guides/code/getting_started/test/controllers/posts_controller_test.rb +7 -0
  207. data/guides/code/getting_started/test/controllers/welcome_controller_test.rb +9 -0
  208. data/guides/code/getting_started/test/fixtures/comments.yml +11 -0
  209. data/guides/code/getting_started/test/fixtures/posts.yml +9 -0
  210. data/guides/code/getting_started/test/helpers/comments_helper_test.rb +4 -0
  211. data/guides/code/getting_started/test/helpers/posts_helper_test.rb +4 -0
  212. data/guides/code/getting_started/test/helpers/welcome_helper_test.rb +4 -0
  213. data/guides/code/getting_started/test/models/comment_test.rb +7 -0
  214. data/guides/code/getting_started/test/models/post_test.rb +7 -0
  215. data/guides/code/getting_started/test/test_helper.rb +15 -0
  216. data/guides/rails_guides.rb +44 -0
  217. data/guides/rails_guides/generator.rb +248 -0
  218. data/guides/rails_guides/helpers.rb +51 -0
  219. data/guides/rails_guides/indexer.rb +68 -0
  220. data/guides/rails_guides/kindle.rb +119 -0
  221. data/guides/rails_guides/levenshtein.rb +31 -0
  222. data/guides/rails_guides/markdown.rb +163 -0
  223. data/guides/rails_guides/markdown/renderer.rb +82 -0
  224. data/guides/source/2_2_release_notes.md +435 -0
  225. data/guides/source/2_3_release_notes.md +621 -0
  226. data/guides/source/3_0_release_notes.md +614 -0
  227. data/guides/source/3_1_release_notes.md +556 -0
  228. data/guides/source/3_2_release_notes.md +565 -0
  229. data/guides/source/4_0_release_notes.md +228 -0
  230. data/guides/source/_license.html.erb +2 -0
  231. data/guides/source/_welcome.html.erb +19 -0
  232. data/guides/source/action_controller_overview.md +872 -0
  233. data/guides/source/action_mailer_basics.md +599 -0
  234. data/guides/source/action_view_overview.md +1565 -0
  235. data/guides/source/active_model_basics.md +200 -0
  236. data/guides/source/active_record_basics.md +370 -0
  237. data/guides/source/active_record_callbacks.md +358 -0
  238. data/guides/source/active_record_querying.md +1621 -0
  239. data/guides/source/active_record_validations.md +1128 -0
  240. data/guides/source/active_support_core_extensions.md +3791 -0
  241. data/guides/source/active_support_instrumentation.md +487 -0
  242. data/guides/source/api_documentation_guidelines.md +209 -0
  243. data/guides/source/asset_pipeline.md +832 -0
  244. data/guides/source/association_basics.md +2129 -0
  245. data/guides/source/caching_with_rails.md +350 -0
  246. data/guides/source/command_line.md +594 -0
  247. data/guides/source/configuring.md +736 -0
  248. data/guides/source/contributing_to_ruby_on_rails.md +455 -0
  249. data/guides/source/credits.html.erb +76 -0
  250. data/guides/source/debugging_rails_applications.md +675 -0
  251. data/guides/source/development_dependencies_install.md +195 -0
  252. data/guides/source/documents.yaml +179 -0
  253. data/guides/source/engines.md +961 -0
  254. data/guides/source/form_helpers.md +955 -0
  255. data/guides/source/generators.md +644 -0
  256. data/guides/source/getting_started.md +1775 -0
  257. data/guides/source/i18n.md +983 -0
  258. data/guides/source/index.html.erb +27 -0
  259. data/guides/source/initialization.md +562 -0
  260. data/guides/source/kindle/KINDLE.md +26 -0
  261. data/guides/source/kindle/copyright.html.erb +1 -0
  262. data/guides/source/kindle/layout.html.erb +27 -0
  263. data/guides/source/kindle/rails_guides.opf.erb +52 -0
  264. data/guides/source/kindle/toc.html.erb +24 -0
  265. data/guides/source/kindle/toc.ncx.erb +64 -0
  266. data/guides/source/kindle/welcome.html.erb +5 -0
  267. data/guides/source/layout.html.erb +148 -0
  268. data/guides/source/layouts_and_rendering.md +1132 -0
  269. data/guides/source/migrations.md +1059 -0
  270. data/guides/source/nested_model_forms.md +225 -0
  271. data/guides/source/plugins.md +435 -0
  272. data/guides/source/rails_application_templates.md +229 -0
  273. data/guides/source/rails_on_rack.md +342 -0
  274. data/guides/source/routing.md +1088 -0
  275. data/guides/source/ruby_on_rails_guides_guidelines.md +124 -0
  276. data/guides/source/security.md +973 -0
  277. data/guides/source/testing.md +981 -0
  278. data/guides/source/upgrading_ruby_on_rails.md +286 -0
  279. data/guides/source/working_with_javascript_in_rails.md +396 -0
  280. data/guides/w3c_validator.rb +95 -0
  281. metadata +315 -31
@@ -0,0 +1,228 @@
1
+ Ruby on Rails 4.0 Release Notes
2
+ ===============================
3
+
4
+ Highlights in Rails 4.0:
5
+
6
+ * Ruby 2.0 preferred; 1.9.3+ required
7
+ * Strong Parameters
8
+ * Turbolinks
9
+ * Russian Doll Caching
10
+
11
+ These release notes cover only the major changes. To know about various bug fixes and changes, please refer to the change logs or check out the [list of commits](https://github.com/rails/rails/commits/master) in the main Rails repository on GitHub.
12
+
13
+ --------------------------------------------------------------------------------
14
+
15
+ Upgrading to Rails 4.0
16
+ ----------------------
17
+
18
+ If you're upgrading an existing application, it's a great idea to have good test coverage before going in. You should also first upgrade to Rails 3.2 in case you haven't and make sure your application still runs as expected before attempting an update to Rails 4.0. A list of things to watch out for when upgrading is available in the [Upgrading to Rails](upgrading_ruby_on_rails.html#upgrading-from-rails-3-2-to-rails-4-0) guide.
19
+
20
+
21
+ Creating a Rails 4.0 application
22
+ --------------------------------
23
+
24
+ ```
25
+ You should have the 'rails' rubygem installed
26
+ $ rails new myapp
27
+ $ cd myapp
28
+ ```
29
+
30
+ ### Vendoring Gems
31
+
32
+ Rails now uses a `Gemfile` in the application root to determine the gems you require for your application to start. This `Gemfile` is processed by the [Bundler](https://github.com/carlhuda/bundler) gem, which then installs all your dependencies. It can even install all the dependencies locally to your application so that it doesn't depend on the system gems.
33
+
34
+ More information: [Bundler homepage](http://gembundler.com)
35
+
36
+ ### Living on the Edge
37
+
38
+ `Bundler` and `Gemfile` makes freezing your Rails application easy as pie with the new dedicated `bundle` command. If you want to bundle straight from the Git repository, you can pass the `--edge` flag:
39
+
40
+ ```
41
+ $ rails new myapp --edge
42
+ ```
43
+
44
+ If you have a local checkout of the Rails repository and want to generate an application using that, you can pass the `--dev` flag:
45
+
46
+ ```
47
+ $ ruby /path/to/rails/railties/bin/rails new myapp --dev
48
+ ```
49
+
50
+ Major Features
51
+ --------------
52
+
53
+ TODO. Give a list and then talk about each of them briefly. We can point to relevant code commits or documentation from these sections.
54
+
55
+ ![Rails 4.0](images/rails4_features.png)
56
+
57
+ Extraction of features to gems
58
+ ---------------------------
59
+
60
+ In Rails 4.0, several features have been extracted into gems. You can simply add the extracted gems to your `Gemfile` to bring the functionality back.
61
+
62
+ * Hash-based & Dynamic finder methods ([Github](https://github.com/rails/activerecord-deprecated_finders))
63
+ * Mass assignment protection in Active Record models ([Github](https://github.com/rails/protected_attributes), [Pull Request](https://github.com/rails/rails/pull/7251))
64
+ * ActiveRecord::SessionStore ([Github](https://github.com/rails/activerecord-session_store), [Pull Request](https://github.com/rails/rails/pull/7436))
65
+ * Active Record Observers ([Github](https://github.com/rails/rails-observers), [Commit](https://github.com/rails/rails/commit/39e85b3b90c58449164673909a6f1893cba290b2))
66
+ * Active Resource ([Github](https://github.com/rails/activeresource), [Pull Request](https://github.com/rails/rails/pull/572), [Blog](http://yetimedia.tumblr.com/post/35233051627/activeresource-is-dead-long-live-activeresource))
67
+ * Action Caching ([Github](https://github.com/rails/actionpack-action_caching), [Pull Request](https://github.com/rails/rails/pull/7833))
68
+ * Page Caching ([Github](https://github.com/rails/actionpack-page_caching), [Pull Request](https://github.com/rails/rails/pull/7833))
69
+ * Sprockets ([Github](https://github.com/rails/sprockets-rails))
70
+ * Performance tests ([Github](https://github.com/rails/rails-perftest), [Pull Request](https://github.com/rails/rails/pull/8876))
71
+
72
+ Documentation
73
+ -------------
74
+
75
+ * Guides are rewritten in GitHub Flavored Markdown.
76
+
77
+ * Guides have a responsive design.
78
+
79
+ Railties
80
+ --------
81
+
82
+ Please refer to the [Changelog](https://github.com/rails/rails/blob/master/railties/CHANGELOG.md) for detailed changes.
83
+
84
+ ### Notable changes
85
+
86
+ * New test locations `test/models`, `test/helpers`, `test/controllers`, and `test/mailers`. Corresponding rake tasks added as well. ([Pull Request](https://github.com/rails/rails/pull/7878))
87
+
88
+ * Your app's executables now live in the `bin/` dir. Run `rake rails:update:bin` to get `bin/bundle`, `bin/rails`, and `bin/rake`.
89
+
90
+ * Threadsafe on by default
91
+
92
+ ### Deprecations
93
+
94
+ * `config.threadsafe!` is deprecated in favor of `config.eager_load` which provides a more fine grained control on what is eager loaded.
95
+
96
+ * `Rails::Plugin` has gone. Instead of adding plugins to `vendor/plugins` use gems or bundler with path or git dependencies.
97
+
98
+ Action Mailer
99
+ -------------
100
+
101
+ Please refer to the [Changelog](https://github.com/rails/rails/blob/master/actionmailer/CHANGELOG.md) for detailed changes.
102
+
103
+ ### Notable changes
104
+
105
+ ### Deprecations
106
+
107
+ Active Model
108
+ ------------
109
+
110
+ Please refer to the [Changelog](https://github.com/rails/rails/blob/master/activemodel/CHANGELOG.md) for detailed changes.
111
+
112
+ ### Notable changes
113
+
114
+ * Add `ActiveModel::ForbiddenAttributesProtection`, a simple module to protect attributes from mass assignment when non-permitted attributes are passed.
115
+
116
+ * Added `ActiveModel::Model`, a mixin to make Ruby objects work with AP out of box.
117
+
118
+ ### Deprecations
119
+
120
+ Active Support
121
+ --------------
122
+
123
+ Please refer to the [Changelog](https://github.com/rails/rails/blob/master/activesupport/CHANGELOG.md) for detailed changes.
124
+
125
+ ### Notable changes
126
+
127
+ * Replace deprecated `memcache-client` gem with `dalli` in ActiveSupport::Cache::MemCacheStore.
128
+
129
+ * Optimize ActiveSupport::Cache::Entry to reduce memory and processing overhead.
130
+
131
+ * Inflections can now be defined per locale. `singularize` and `pluralize` accept locale as an extra argument.
132
+
133
+ * `Object#try` will now return nil instead of raise a NoMethodError if the receiving object does not implement the method, but you can still get the old behavior by using the new `Object#try!`.
134
+
135
+ ### Deprecations
136
+
137
+ * Deprecate `ActiveSupport::TestCase#pending` method, use `skip` from MiniTest instead.
138
+
139
+ * ActiveSupport::Benchmarkable#silence has been deprecated due to its lack of thread safety. It will be removed without replacement in Rails 4.1.
140
+
141
+ * `ActiveSupport::JSON::Variable` is deprecated. Define your own `#as_json` and `#encode_json` methods for custom JSON string literals.
142
+
143
+ * Deprecates the compatibility method Module#local_constant_names, use Module#local_constants instead (which returns symbols).
144
+
145
+ * BufferedLogger is deprecated. Use ActiveSupport::Logger, or the logger from Ruby stdlib.
146
+
147
+ * Deprecate `assert_present` and `assert_blank` in favor of `assert object.blank?` and `assert object.present?`
148
+
149
+ Action Pack
150
+ -----------
151
+
152
+ Please refer to the [Changelog](https://github.com/rails/rails/blob/master/actionpack/CHANGELOG.md) for detailed changes.
153
+
154
+ ### Notable changes
155
+
156
+ * Change the stylesheet of exception pages for development mode. Additionally display also the line of code and fragment that raised the exception in all exceptions pages.
157
+
158
+ ### Deprecations
159
+
160
+
161
+ Active Record
162
+ -------------
163
+
164
+ Please refer to the [Changelog](https://github.com/rails/rails/blob/master/activerecord/CHANGELOG.md) for detailed changes.
165
+
166
+ ### Notable changes
167
+
168
+ * Improve ways to write `change` migrations, making the old `up` & `down` methods no longer necessary.
169
+
170
+ * The methods `drop_table` and `remove_column` are now reversible, as long as the necessary information is given.
171
+ The method `remove_column` used to accept multiple column names; instead use `remove_columns` (which is not revertible).
172
+ The method `change_table` is also reversible, as long as its block doesn't call `remove`, `change` or `change_default`
173
+
174
+ * New method `reversible` makes it possible to specify code to be run when migrating up or down.
175
+ See the [Guide on Migration](https://github.com/rails/rails/blob/master/guides/source/migrations.md#using-the-reversible-method)
176
+
177
+ * New method `revert` will revert a whole migration or the given block.
178
+ If migrating down, the given migration / block is run normally.
179
+ See the [Guide on Migration](https://github.com/rails/rails/blob/master/guides/source/migrations.md#reverting-previous-migrations)
180
+
181
+ * Adds some metadata columns to `schema_migrations` table.
182
+
183
+ * `migrated_at`
184
+ * `fingerprint` - an md5 hash of the migration.
185
+ * `name` - the filename minus version and extension.
186
+
187
+ * Adds PostgreSQL array type support. Any datatype can be used to create an array column, with full migration and schema dumper support.
188
+
189
+ * Add `Relation#load` to explicitly load the record and return `self`.
190
+
191
+ * `Model.all` now returns an `ActiveRecord::Relation`, rather than an array of records. Use `Relation#to_a` if you really want an array. In some specific cases, this may cause breakage when upgrading.
192
+
193
+ * Added `ActiveRecord::Migration.check_pending!` that raises an error if migrations are pending.
194
+
195
+ * Added custom coders support for `ActiveRecord::Store`. Now you can set your custom coder like this:
196
+
197
+ store :settings, accessors: [ :color, :homepage ], coder: JSON
198
+
199
+ * `mysql` and `mysql2` connections will set `SQL_MODE=STRICT_ALL_TABLES` by default to avoid silent data loss. This can be disabled by specifying `strict: false` in your `database.yml`.
200
+
201
+ * Remove IdentityMap.
202
+
203
+ * Remove automatic execution of EXPLAIN queries. The option `active_record.auto_explain_threshold_in_seconds` is no longer used and should be removed.
204
+
205
+ * Adds `ActiveRecord::NullRelation` and `ActiveRecord::Relation#none` implementing the null object pattern for the Relation class.
206
+
207
+ * Added `create_join_table` migration helper to create HABTM join tables.
208
+
209
+ * Allows PostgreSQL hstore records to be created.
210
+
211
+ ### Deprecations
212
+
213
+ * Deprecated the old-style hash based finder API. This means that methods which previously accepted "finder options" no longer do.
214
+
215
+ * All dynamic methods except for `find_by_...` and `find_by_...!` are deprecated. Here's
216
+ how you can rewrite the code:
217
+
218
+ * `find_all_by_...` can be rewritten using `where(...)`.
219
+ * `find_last_by_...` can be rewritten using `where(...).last`.
220
+ * `scoped_by_...` can be rewritten using `where(...)`.
221
+ * `find_or_initialize_by_...` can be rewritten using `where(...).first_or_initialize`.
222
+ * `find_or_create_by_...` can be rewritten using `find_or_create_by(...)` or `where(...).first_or_create`.
223
+ * `find_or_create_by_...!` can be rewritten using `find_or_create_by!(...)` or `where(...).first_or_create!`.
224
+
225
+ Credits
226
+ -------
227
+
228
+ See the [full list of contributors to Rails](http://contributors.rubyonrails.org/) for the many people who spent many hours making Rails, the stable and robust framework it is. Kudos to all of them.
@@ -0,0 +1,2 @@
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>
@@ -0,0 +1,19 @@
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 3.2 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 2.3.x are available at <a href="http://guides.rubyonrails.org/v2.3.11/">http://guides.rubyonrails.org/v2.3.11/</a>.
19
+ </p>
@@ -0,0 +1,872 @@
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
+ * Why and how to store data in the session or cookies.
10
+ * How to work with filters to execute code during request processing.
11
+ * How to use Action Controller's built-in HTTP authentication.
12
+ * How to stream data directly to the user's browser.
13
+ * How to filter sensitive parameters so they do not appear in the application's log.
14
+ * How to deal with exceptions that may be raised during request processing.
15
+
16
+ --------------------------------------------------------------------------------
17
+
18
+ What Does a Controller Do?
19
+ --------------------------
20
+
21
+ 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.
22
+
23
+ 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.
24
+
25
+ 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.
26
+
27
+ NOTE: For more details on the routing process, see [Rails Routing from the Outside In](routing.html).
28
+
29
+ Methods and Actions
30
+ -------------------
31
+
32
+ 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.
33
+
34
+ ```ruby
35
+ class ClientsController < ApplicationController
36
+ def new
37
+ end
38
+ end
39
+ ```
40
+
41
+ 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 could 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`:
42
+
43
+ ```ruby
44
+ def new
45
+ @client = Client.new
46
+ end
47
+ ```
48
+
49
+ The [Layouts & Rendering Guide](layouts_and_rendering.html) explains this in more detail.
50
+
51
+ `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.
52
+
53
+ 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.
54
+
55
+ Parameters
56
+ ----------
57
+
58
+ 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:
59
+
60
+ ```ruby
61
+ class ClientsController < ApplicationController
62
+ # This action uses query string parameters because it gets run
63
+ # by an HTTP GET request, but this does not make any difference
64
+ # to the way in which the parameters are accessed. The URL for
65
+ # this action would look like this in order to list activated
66
+ # clients: /clients?status=activated
67
+ def index
68
+ if params[:status] == "activated"
69
+ @clients = Client.activated
70
+ else
71
+ @clients = Client.inactivated
72
+ end
73
+ end
74
+
75
+ # This action uses POST parameters. They are most likely coming
76
+ # from an HTML form which the user has submitted. The URL for
77
+ # this RESTful request will be "/clients", and the data will be
78
+ # sent as part of the request body.
79
+ def create
80
+ @client = Client.new(params[:client])
81
+ if @client.save
82
+ redirect_to @client
83
+ else
84
+ # This line overrides the default rendering behavior, which
85
+ # would have been to render the "create" view.
86
+ render "new"
87
+ end
88
+ end
89
+ end
90
+ ```
91
+
92
+ ### Hash and Array Parameters
93
+
94
+ 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:
95
+
96
+ ```
97
+ GET /clients?ids[]=1&ids[]=2&ids[]=3
98
+ ```
99
+
100
+ 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.
101
+
102
+ 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.
103
+
104
+ To send a hash you include the key name inside the brackets:
105
+
106
+ ```html
107
+ <form accept-charset="UTF-8" action="/clients" method="post">
108
+ <input type="text" name="client[name]" value="Acme" />
109
+ <input type="text" name="client[phone]" value="12345" />
110
+ <input type="text" name="client[address][postcode]" value="12345" />
111
+ <input type="text" name="client[address][city]" value="Carrot City" />
112
+ </form>
113
+ ```
114
+
115
+ 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]`.
116
+
117
+ Note that the `params` hash is actually an instance of `ActiveSupport::HashWithIndifferentAccess`, which acts like a hash that lets you use symbols and strings interchangeably as keys.
118
+
119
+ ### JSON parameters
120
+
121
+ If you're writing a web service application, you might find yourself more comfortable on accepting parameters in JSON format. Rails will automatically convert your parameters into `params` hash, which you'll be able to access like you would normally do with form data.
122
+
123
+ So for example, if you are sending this JSON parameter:
124
+
125
+ ```json
126
+ { "company": { "name": "acme", "address": "123 Carrot Street" } }
127
+ ```
128
+
129
+ You'll get `params[:company]` as `{ :name => "acme", "address" => "123 Carrot Street" }`.
130
+
131
+ 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:
132
+
133
+ ```json
134
+ { "name": "acme", "address": "123 Carrot Street" }
135
+ ```
136
+
137
+ And assume that you're sending the data to `CompaniesController`, it would then be wrapped in `:company` key like this:
138
+
139
+ ```ruby
140
+ { :name => "acme", :address => "123 Carrot Street", :company => { :name => "acme", :address => "123 Carrot Street" }}
141
+ ```
142
+
143
+ 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)
144
+
145
+ NOTE: A support for parsing XML parameters has been extracted into a gem named `actionpack-xml_parser`
146
+
147
+ ### Routing Parameters
148
+
149
+ 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:
150
+
151
+ ```ruby
152
+ match '/clients/:status' => 'clients#index', foo: "bar"
153
+ ```
154
+
155
+ 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".
156
+
157
+ ### `default_url_options`
158
+
159
+ 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:
160
+
161
+ ```ruby
162
+ class ApplicationController < ActionController::Base
163
+ def default_url_options
164
+ { locale: I18n.locale }
165
+ end
166
+ end
167
+ ```
168
+
169
+ 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.
170
+
171
+ 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.
172
+
173
+
174
+ Session
175
+ -------
176
+
177
+ 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:
178
+
179
+ * `ActionDispatch::Session::CookieStore` - Stores everything on the client.
180
+ * `ActionDispatch::Session::CacheStore` - Stores the data in the Rails cache.
181
+ * `ActionDispatch::Session::ActiveRecordStore` - Stores the data in a database using Active Record. (require `activerecord-session_store` gem).
182
+ * `ActionDispatch::Session::MemCacheStore` - Stores the data in a memcached cluster (this is a legacy implementation; consider using CacheStore instead).
183
+
184
+ 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).
185
+
186
+ For most stores, this ID is used to look up the session data on the server, e.g. in a database table. There is one exception, and that is the default and recommended session store - the CookieStore - which stores all session data in the cookie itself (the ID is still available to you if you need it). This has the advantage of being very lightweight and it requires zero setup in a new application in order to use the session. The cookie data is cryptographically signed to make it tamper-proof, but it is not encrypted, so anyone with access to it can read its contents but not edit it (Rails will not accept it if it has been edited).
187
+
188
+ 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.
189
+
190
+ 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.
191
+
192
+ Read more about session storage in the [Security Guide](security.html).
193
+
194
+ If you need a different session storage mechanism, you can change it in the `config/initializers/session_store.rb` file:
195
+
196
+ ```ruby
197
+ # Use the database for sessions instead of the cookie-based default,
198
+ # which shouldn't be used to store highly confidential information
199
+ # (create the session table with "rails g active_record:session_migration")
200
+ # YourApp::Application.config.session_store :active_record_store
201
+ ```
202
+
203
+ 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`:
204
+
205
+ ```ruby
206
+ # Be sure to restart your server when you modify this file.
207
+ YourApp::Application.config.session_store :cookie_store, key: '_your_app_session'
208
+ ```
209
+
210
+ You can also pass a `:domain` key and specify the domain name for the cookie:
211
+
212
+ ```ruby
213
+ # Be sure to restart your server when you modify this file.
214
+ YourApp::Application.config.session_store :cookie_store, key: '_your_app_session', domain: ".example.com"
215
+ ```
216
+
217
+ 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`
218
+
219
+ ```ruby
220
+ # Be sure to restart your server when you modify this file.
221
+
222
+ # Your secret key for verifying the integrity of signed cookies.
223
+ # If you change this key, all old signed cookies will become invalid!
224
+ # Make sure the secret is at least 30 characters and all random,
225
+ # no regular words or you'll be exposed to dictionary attacks.
226
+ YourApp::Application.config.secret_key_base = '49d3f3de9ed86c74b94ad6bd0...'
227
+ ```
228
+
229
+ NOTE: Changing the secret when using the `CookieStore` will invalidate all existing sessions.
230
+
231
+ ### Accessing the Session
232
+
233
+ In your controller you can access the session through the `session` instance method.
234
+
235
+ 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.
236
+
237
+ Session values are stored using key/value pairs like a hash:
238
+
239
+ ```ruby
240
+ class ApplicationController < ActionController::Base
241
+
242
+ private
243
+
244
+ # Finds the User with the ID stored in the session with the key
245
+ # :current_user_id This is a common way to handle user login in
246
+ # a Rails application; logging in sets the session value and
247
+ # logging out removes it.
248
+ def current_user
249
+ @_current_user ||= session[:current_user_id] &&
250
+ User.find_by_id(session[:current_user_id])
251
+ end
252
+ end
253
+ ```
254
+
255
+ To store something in the session, just assign it to the key like a hash:
256
+
257
+ ```ruby
258
+ class LoginsController < ApplicationController
259
+ # "Create" a login, aka "log the user in"
260
+ def create
261
+ if user = User.authenticate(params[:username], params[:password])
262
+ # Save the user ID in the session so it can be used in
263
+ # subsequent requests
264
+ session[:current_user_id] = user.id
265
+ redirect_to root_url
266
+ end
267
+ end
268
+ end
269
+ ```
270
+
271
+ To remove something from the session, assign that key to be `nil`:
272
+
273
+ ```ruby
274
+ class LoginsController < ApplicationController
275
+ # "Delete" a login, aka "log the user out"
276
+ def destroy
277
+ # Remove the user id from the session
278
+ @_current_user = session[:current_user_id] = nil
279
+ redirect_to root_url
280
+ end
281
+ end
282
+ ```
283
+
284
+ To reset the entire session, use `reset_session`.
285
+
286
+ ### The Flash
287
+
288
+ 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.
289
+
290
+ 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).
291
+
292
+ 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:
293
+
294
+ ```ruby
295
+ class LoginsController < ApplicationController
296
+ def destroy
297
+ session[:current_user_id] = nil
298
+ flash[:notice] = "You have successfully logged out."
299
+ redirect_to root_url
300
+ end
301
+ end
302
+ ```
303
+
304
+ 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`:
305
+
306
+ ```ruby
307
+ redirect_to root_url, notice: "You have successfully logged out."
308
+ redirect_to root_url, alert: "You're stuck here!"
309
+ redirect_to root_url, flash: { referral_code: 1234 }
310
+ ```
311
+
312
+ 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:
313
+
314
+ ```erb
315
+ <html>
316
+ <!-- <head/> -->
317
+ <body>
318
+ <% flash.each do |name, msg| -%>
319
+ <%= content_tag :div, msg, class: name %>
320
+ <% end -%>
321
+
322
+ <!-- more content -->
323
+ </body>
324
+ </html>
325
+ ```
326
+
327
+ This way, if an action sets a notice or an alert message, the layout will display it automatically.
328
+
329
+ You can pass anything that the session can store; you're not limited to notices and alerts:
330
+
331
+ ```erb
332
+ <% if flash[:just_signed_up] %>
333
+ <p class="welcome">Welcome to our site!</p>
334
+ <% end %>
335
+ ```
336
+
337
+ If you want a flash value to be carried over to another request, use the `keep` method:
338
+
339
+ ```ruby
340
+ class MainController < ApplicationController
341
+ # Let's say this action corresponds to root_url, but you want
342
+ # all requests here to be redirected to UsersController#index.
343
+ # If an action sets the flash and redirects here, the values
344
+ # would normally be lost when another redirect happens, but you
345
+ # can use 'keep' to make it persist for another request.
346
+ def index
347
+ # Will persist all flash values.
348
+ flash.keep
349
+
350
+ # You can also use a key to keep only some kind of value.
351
+ # flash.keep(:notice)
352
+ redirect_to users_url
353
+ end
354
+ end
355
+ ```
356
+
357
+ #### `flash.now`
358
+
359
+ 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`:
360
+
361
+ ```ruby
362
+ class ClientsController < ApplicationController
363
+ def create
364
+ @client = Client.new(params[:client])
365
+ if @client.save
366
+ # ...
367
+ else
368
+ flash.now[:error] = "Could not save client"
369
+ render action: "new"
370
+ end
371
+ end
372
+ end
373
+ ```
374
+
375
+ Cookies
376
+ -------
377
+
378
+ 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:
379
+
380
+ ```ruby
381
+ class CommentsController < ApplicationController
382
+ def new
383
+ # Auto-fill the commenter's name if it has been stored in a cookie
384
+ @comment = Comment.new(author: cookies[:commenter_name])
385
+ end
386
+
387
+ def create
388
+ @comment = Comment.new(params[:comment])
389
+ if @comment.save
390
+ flash[:notice] = "Thanks for your comment!"
391
+ if params[:remember_name]
392
+ # Remember the commenter's name.
393
+ cookies[:commenter_name] = @comment.author
394
+ else
395
+ # Delete cookie for the commenter's name cookie, if any.
396
+ cookies.delete(:commenter_name)
397
+ end
398
+ redirect_to @comment.article
399
+ else
400
+ render action: "new"
401
+ end
402
+ end
403
+ end
404
+ ```
405
+
406
+ Note that while for session values you set the key to `nil`, to delete a cookie value you should use `cookies.delete(:key)`.
407
+
408
+ Rendering xml and json data
409
+ ---------------------------
410
+
411
+ ActionController makes it extremely easy to render `xml` or `json` data. If you generate a controller using scaffolding then it would look something like this:
412
+
413
+ ```ruby
414
+ class UsersController < ApplicationController
415
+ def index
416
+ @users = User.all
417
+ respond_to do |format|
418
+ format.html # index.html.erb
419
+ format.xml { render xml: @users}
420
+ format.json { render json: @users}
421
+ end
422
+ end
423
+ end
424
+ ```
425
+
426
+ Notice that in the above case code is `render xml: @users` and not `render xml: @users.to_xml`. That is because if the input is not string then rails automatically invokes `to_xml` .
427
+
428
+ Filters
429
+ -------
430
+
431
+ Filters are methods that are run before, after or "around" a controller action.
432
+
433
+ Filters are inherited, so if you set a filter on `ApplicationController`, it will be run on every controller in your application.
434
+
435
+ "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:
436
+
437
+ ```ruby
438
+ class ApplicationController < ActionController::Base
439
+ before_action :require_login
440
+
441
+ private
442
+
443
+ def require_login
444
+ unless logged_in?
445
+ flash[:error] = "You must be logged in to access this section"
446
+ redirect_to new_login_url # halts request cycle
447
+ end
448
+ end
449
+
450
+ # The logged_in? method simply returns true if the user is logged
451
+ # in and false otherwise. It does this by "booleanizing" the
452
+ # current_user method we created previously using a double ! operator.
453
+ # Note that this is not common in Ruby and is discouraged unless you
454
+ # really mean to convert something into true or false.
455
+ def logged_in?
456
+ !!current_user
457
+ end
458
+ end
459
+ ```
460
+
461
+ 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.
462
+
463
+ 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`:
464
+
465
+ ```ruby
466
+ class LoginsController < ApplicationController
467
+ skip_before_action :require_login, only: [:new, :create]
468
+ end
469
+ ```
470
+
471
+ 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.
472
+
473
+ ### After Filters and Around Filters
474
+
475
+ In addition to "before" filters, you can also run filters after an action has been executed, or both before and after.
476
+
477
+ "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.
478
+
479
+ "Around" filters are responsible for running their associated actions by yielding, similar to how Rack middlewares work.
480
+
481
+ 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:
482
+
483
+ ```ruby
484
+ class ChangesController < ApplicationController
485
+ around_action :wrap_in_transaction, only: :show
486
+
487
+ private
488
+
489
+ def wrap_in_transaction
490
+ ActiveRecord::Base.transaction do
491
+ begin
492
+ yield
493
+ ensure
494
+ raise ActiveRecord::Rollback
495
+ end
496
+ end
497
+ end
498
+ end
499
+ ```
500
+
501
+ 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.
502
+
503
+ You can choose not to yield and build the response yourself, in which case the action will not be run.
504
+
505
+ ### Other Ways to Use Filters
506
+
507
+ 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.
508
+
509
+ 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:
510
+
511
+ ```ruby
512
+ class ApplicationController < ActionController::Base
513
+ before_action do |controller|
514
+ redirect_to new_login_url unless controller.send(:logged_in?)
515
+ end
516
+ end
517
+ ```
518
+
519
+ 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.
520
+
521
+ The second way is to use a class (actually, any object that responds to the right methods will do) to handle the filtering. This is useful in cases that are more complex and can not be implemented in a readable and reusable way using the two other methods. As an example, you could rewrite the login filter again to use a class:
522
+
523
+ ```ruby
524
+ class ApplicationController < ActionController::Base
525
+ before_action LoginFilter
526
+ end
527
+
528
+ class LoginFilter
529
+ def self.filter(controller)
530
+ unless controller.send(:logged_in?)
531
+ controller.flash[:error] = "You must be logged in"
532
+ controller.redirect_to controller.new_login_url
533
+ end
534
+ end
535
+ end
536
+ ```
537
+
538
+ Again, this is not an ideal example for this filter, because it's not run in the scope of the controller but gets the controller passed as an argument. The filter class has a class method `filter` which gets run before or after the action, depending on if it's a before or after filter. Classes used as around filters can also use the same `filter` method, which will get run in the same way. The method must `yield` to execute the action. Alternatively, it can have both a `before` and an `after` method that are run before and after the action.
539
+
540
+ Request Forgery Protection
541
+ --------------------------
542
+
543
+ 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.
544
+
545
+ 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.
546
+
547
+ 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.
548
+
549
+ If you generate a form like this:
550
+
551
+ ```erb
552
+ <%= form_for @user do |f| %>
553
+ <%= f.text_field :username %>
554
+ <%= f.text_field :password %>
555
+ <% end %>
556
+ ```
557
+
558
+ You will see how the token gets added as a hidden field:
559
+
560
+ ```html
561
+ <form accept-charset="UTF-8" action="/users/1" method="post">
562
+ <input type="hidden"
563
+ value="67250ab105eb5ad10851c00a5621854a23af5489"
564
+ name="authenticity_token"/>
565
+ <!-- fields -->
566
+ </form>
567
+ ```
568
+
569
+ 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`:
570
+
571
+ 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.
572
+
573
+ 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.
574
+
575
+ The Request and Response Objects
576
+ --------------------------------
577
+
578
+ 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.
579
+
580
+ ### The `request` Object
581
+
582
+ 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:
583
+
584
+ | Property of `request` | Purpose |
585
+ | ----------------------------------------- | -------------------------------------------------------------------------------- |
586
+ | host | The hostname used for this request. |
587
+ | domain(n=2) | The hostname's first `n` segments, starting from the right (the TLD). |
588
+ | format | The content type requested by the client. |
589
+ | method | The HTTP method used for the request. |
590
+ | get?, post?, patch?, put?, delete?, head? | Returns true if the HTTP method is GET/POST/PATCH/PUT/DELETE/HEAD. |
591
+ | headers | Returns a hash containing the headers associated with the request. |
592
+ | port | The port number (integer) used for the request. |
593
+ | protocol | Returns a string containing the protocol used plus "://", for example "http://". |
594
+ | query_string | The query string part of the URL, i.e., everything after "?". |
595
+ | remote_ip | The IP address of the client. |
596
+ | url | The entire URL used for the request. |
597
+
598
+ #### `path_parameters`, `query_parameters`, and `request_parameters`
599
+
600
+ 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.
601
+
602
+ ### The `response` Object
603
+
604
+ 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.
605
+
606
+ | Property of `response` | Purpose |
607
+ | ---------------------- | --------------------------------------------------------------------------------------------------- |
608
+ | body | This is the string of data being sent back to the client. This is most often HTML. |
609
+ | status | The HTTP status code for the response, like 200 for a successful request or 404 for file not found. |
610
+ | location | The URL the client is being redirected to, if any. |
611
+ | content_type | The content type of the response. |
612
+ | charset | The character set being used for the response. Default is "utf-8". |
613
+ | headers | Headers used for the response. |
614
+
615
+ #### Setting Custom Headers
616
+
617
+ 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:
618
+
619
+ ```ruby
620
+ response.headers["Content-Type"] = "application/pdf"
621
+ ```
622
+
623
+ Note: in the above case it would make more sense to use the `content_type` setter directly.
624
+
625
+ HTTP Authentications
626
+ --------------------
627
+
628
+ Rails comes with two built-in HTTP authentication mechanisms:
629
+
630
+ * Basic Authentication
631
+ * Digest Authentication
632
+
633
+ ### HTTP Basic Authentication
634
+
635
+ 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`.
636
+
637
+ ```ruby
638
+ class AdminController < ApplicationController
639
+ http_basic_authenticate_with name: "humbaba", password: "5baa61e4"
640
+ end
641
+ ```
642
+
643
+ With this in place, you can create namespaced controllers that inherit from `AdminController`. The filter will thus be run for all actions in those controllers, protecting them with HTTP basic authentication.
644
+
645
+ ### HTTP Digest Authentication
646
+
647
+ 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`.
648
+
649
+ ```ruby
650
+ class AdminController < ApplicationController
651
+ USERS = { "lifo" => "world" }
652
+
653
+ before_action :authenticate
654
+
655
+ private
656
+
657
+ def authenticate
658
+ authenticate_or_request_with_http_digest do |username|
659
+ USERS[username]
660
+ end
661
+ end
662
+ end
663
+ ```
664
+
665
+ 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.
666
+
667
+ Streaming and File Downloads
668
+ ----------------------------
669
+
670
+ 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.
671
+
672
+ To stream data to the client, use `send_data`:
673
+
674
+ ```ruby
675
+ require "prawn"
676
+ class ClientsController < ApplicationController
677
+ # Generates a PDF document with information on the client and
678
+ # returns it. The user will get the PDF as a file download.
679
+ def download_pdf
680
+ client = Client.find(params[:id])
681
+ send_data generate_pdf(client),
682
+ filename: "#{client.name}.pdf",
683
+ type: "application/pdf"
684
+ end
685
+
686
+ private
687
+
688
+ def generate_pdf(client)
689
+ Prawn::Document.new do
690
+ text client.name, align: :center
691
+ text "Address: #{client.address}"
692
+ text "Email: #{client.email}"
693
+ end.render
694
+ end
695
+ end
696
+ ```
697
+
698
+ 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".
699
+
700
+ ### Sending Files
701
+
702
+ If you want to send a file that already exists on disk, use the `send_file` method.
703
+
704
+ ```ruby
705
+ class ClientsController < ApplicationController
706
+ # Stream a file that has already been generated and stored on disk.
707
+ def download_pdf
708
+ client = Client.find(params[:id])
709
+ send_file("#{Rails.root}/files/clients/#{client.id}.pdf",
710
+ filename: "#{client.name}.pdf",
711
+ type: "application/pdf")
712
+ end
713
+ end
714
+ ```
715
+
716
+ 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.
717
+
718
+ 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.
719
+
720
+ 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.
721
+
722
+ 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.
723
+
724
+ ### RESTful Downloads
725
+
726
+ 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:
727
+
728
+ ```ruby
729
+ class ClientsController < ApplicationController
730
+ # The user can request to receive this resource as HTML or PDF.
731
+ def show
732
+ @client = Client.find(params[:id])
733
+
734
+ respond_to do |format|
735
+ format.html
736
+ format.pdf { render pdf: generate_pdf(@client) }
737
+ end
738
+ end
739
+ end
740
+ ```
741
+
742
+ 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`:
743
+
744
+ ```ruby
745
+ Mime::Type.register "application/pdf", :pdf
746
+ ```
747
+
748
+ NOTE: Configuration files are not reloaded on each request, so you have to restart the server in order for their changes to take effect.
749
+
750
+ Now the user can request to get a PDF version of a client just by adding ".pdf" to the URL:
751
+
752
+ ```bash
753
+ GET /clients/1.pdf
754
+ ```
755
+
756
+ Log Filtering
757
+ -------------
758
+
759
+ 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.
760
+
761
+ ### Parameters Filtering
762
+
763
+ 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.
764
+
765
+ ```ruby
766
+ config.filter_parameters << :password
767
+ ```
768
+
769
+ ### Redirects Filtering
770
+
771
+ Sometimes it's desirable to filter out from log files some sensible locations your application is redirecting to.
772
+ You can do that by using the `config.filter_redirect` configuration option:
773
+
774
+ ```ruby
775
+ config.filter_redirect << 's3.amazonaws.com'
776
+ ```
777
+
778
+ You can set it to a String, a Regexp, or an array of both.
779
+
780
+ ```ruby
781
+ config.filter_redirect.concat ['s3.amazonaws.com', /private_path/]
782
+ ```
783
+
784
+ Matching URLs will be marked as '[FILTERED]'.
785
+
786
+ Rescue
787
+ ------
788
+
789
+ 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.
790
+
791
+ 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:
792
+
793
+ ### The Default 500 and 404 Templates
794
+
795
+ 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.
796
+
797
+ ### `rescue_from`
798
+
799
+ 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.
800
+
801
+ 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.
802
+
803
+ Here's how you can use `rescue_from` to intercept all `ActiveRecord::RecordNotFound` errors and do something with them.
804
+
805
+ ```ruby
806
+ class ApplicationController < ActionController::Base
807
+ rescue_from ActiveRecord::RecordNotFound, with: :record_not_found
808
+
809
+ private
810
+
811
+ def record_not_found
812
+ render text: "404 Not Found", status: 404
813
+ end
814
+ end
815
+ ```
816
+
817
+ 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:
818
+
819
+ ```ruby
820
+ class ApplicationController < ActionController::Base
821
+ rescue_from User::NotAuthorized, with: :user_not_authorized
822
+
823
+ private
824
+
825
+ def user_not_authorized
826
+ flash[:error] = "You don't have access to this section."
827
+ redirect_to :back
828
+ end
829
+ end
830
+
831
+ class ClientsController < ApplicationController
832
+ # Check that the user has the right authorization to access clients.
833
+ before_action :check_authorization
834
+
835
+ # Note how the actions don't have to worry about all the auth stuff.
836
+ def edit
837
+ @client = Client.find(params[:id])
838
+ end
839
+
840
+ private
841
+
842
+ # If the user is not authorized, just throw the exception.
843
+ def check_authorization
844
+ raise User::NotAuthorized unless current_user.admin?
845
+ end
846
+ end
847
+ ```
848
+
849
+ 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.
850
+
851
+ Force HTTPS protocol
852
+ --------------------
853
+
854
+ 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:
855
+
856
+ ```ruby
857
+ class DinnerController
858
+ force_ssl
859
+ end
860
+ ```
861
+
862
+ Just like the filter, you could also pass `:only` and `:except` to enforce the secure connection only to specific actions:
863
+
864
+ ```ruby
865
+ class DinnerController
866
+ force_ssl only: :cheeseburger
867
+ # or
868
+ force_ssl except: :cheeseburger
869
+ end
870
+ ```
871
+
872
+ 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.