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,1775 @@
1
+ Getting Started with Rails
2
+ ==========================
3
+
4
+ This guide covers getting up and running with Ruby on Rails.
5
+
6
+ After reading this guide, you will know:
7
+
8
+ * How to install Rails, create a new Rails application, and connect your
9
+ application to a database.
10
+ * The general layout of a Rails application.
11
+ * The basic principles of MVC (Model, View, Controller) and RESTful design.
12
+ * How to quickly generate the starting pieces of a Rails application.
13
+
14
+ --------------------------------------------------------------------------------
15
+
16
+ Guide Assumptions
17
+ -----------------
18
+
19
+ This guide is designed for beginners who want to get started with a Rails
20
+ application from scratch. It does not assume that you have any prior experience
21
+ with Rails. However, to get the most out of it, you need to have some
22
+ prerequisites installed:
23
+
24
+ * The [Ruby](http://www.ruby-lang.org/en/downloads) language version 1.9.3 or newer
25
+ * The [RubyGems](http://rubygems.org/) packaging system
26
+ * To learn more about RubyGems, please read the [RubyGems User Guide](http://docs.rubygems.org/read/book/1)
27
+ * A working installation of the [SQLite3 Database](http://www.sqlite.org)
28
+
29
+ Rails is a web application framework running on the Ruby programming language.
30
+ If you have no prior experience with Ruby, you will find a very steep learning
31
+ curve diving straight into Rails. There are some good free resources on the
32
+ internet for learning Ruby, including:
33
+
34
+ * [Mr. Neighborly's Humble Little Ruby Book](http://www.humblelittlerubybook.com)
35
+ * [Programming Ruby](http://www.ruby-doc.org/docs/ProgrammingRuby/)
36
+ * [Why's (Poignant) Guide to Ruby](http://mislav.uniqpath.com/poignant-guide/)
37
+
38
+ What is Rails?
39
+ --------------
40
+
41
+ Rails is a web application development framework written in the Ruby language.
42
+ It is designed to make programming web applications easier by making assumptions
43
+ about what every developer needs to get started. It allows you to write less
44
+ code while accomplishing more than many other languages and frameworks.
45
+ Experienced Rails developers also report that it makes web application
46
+ development more fun.
47
+
48
+ Rails is opinionated software. It makes the assumption that there is the "best"
49
+ way to do things, and it's designed to encourage that way - and in some cases to
50
+ discourage alternatives. If you learn "The Rails Way" you'll probably discover a
51
+ tremendous increase in productivity. If you persist in bringing old habits from
52
+ other languages to your Rails development, and trying to use patterns you
53
+ learned elsewhere, you may have a less happy experience.
54
+
55
+ The Rails philosophy includes two major guiding principles:
56
+
57
+ * DRY - "Don't Repeat Yourself" - suggests that writing the same code over and over again is a bad thing.
58
+ * Convention Over Configuration - means that Rails makes assumptions about what you want to do and how you're going to
59
+ do it, rather than requiring you to specify every little thing through endless configuration files.
60
+
61
+ Creating a New Rails Project
62
+ ----------------------------
63
+
64
+ The best way to use this guide is to follow each step as it happens, no code or
65
+ step needed to make this example application has been left out, so you can
66
+ literally follow along step by step. You can get the complete code
67
+ [here](https://github.com/lifo/docrails/tree/master/guides/code/getting_started).
68
+
69
+ By following along with this guide, you'll create a Rails project called
70
+ `blog`, a
71
+ (very) simple weblog. Before you can start building the application, you need to
72
+ make sure that you have Rails itself installed.
73
+
74
+ TIP: The examples below use `#` and `$` to denote superuser and regular
75
+ user terminal prompts respectively in a UNIX-like OS. If you are using
76
+ Windows, your prompt will look something like `c:\source_code>`
77
+
78
+ ### Installing Rails
79
+
80
+ Open up a command line prompt. On Mac OS X open Terminal.app, on Windows choose
81
+ "Run" from your Start menu and type 'cmd.exe'. Any commands prefaced with a
82
+ dollar sign `$` should be run in the command line. Verify that you have a
83
+ current version of Ruby installed:
84
+
85
+ ```bash
86
+ $ ruby -v
87
+ ruby 1.9.3p385
88
+ ```
89
+
90
+ To install Rails, use the `gem install` command provided by RubyGems:
91
+
92
+ ```bash
93
+ $ gem install rails
94
+ ```
95
+
96
+ TIP. A number of tools exist to help you quickly install Ruby and Ruby
97
+ on Rails on your system. Windows users can use [Rails Installer](http://railsinstaller.org), while Mac OS X users can use
98
+ [Rails One Click](http://railsoneclick.com).
99
+
100
+ To verify that you have everything installed correctly, you should be able to run the following:
101
+
102
+ ```bash
103
+ $ rails --version
104
+ ```
105
+
106
+ If it says something like "Rails 3.2.9", you are ready to continue.
107
+
108
+ ### Creating the Blog Application
109
+
110
+ Rails comes with a number of scripts called generators that are designed to make your development life easier by creating everything that's necessary to start working on a particular task. One of these is the new application generator, which will provide you with the foundation of a fresh Rails application so that you don't have to write it yourself.
111
+
112
+ To use this generator, open a terminal, navigate to a directory where you have rights to create files, and type:
113
+
114
+ ```bash
115
+ $ rails new blog
116
+ ```
117
+
118
+ This will create a Rails application called Blog in a directory called blog and install the gem dependencies that are already mentioned in `Gemfile` using `bundle install`.
119
+
120
+ TIP: You can see all of the command line options that the Rails
121
+ application builder accepts by running `rails new -h`.
122
+
123
+ After you create the blog application, switch to its folder to continue work directly in that application:
124
+
125
+ ```bash
126
+ $ cd blog
127
+ ```
128
+
129
+ The `rails new blog` command we ran above created a folder in your
130
+ working directory called `blog`. The `blog` directory has a number of
131
+ auto-generated files and folders that make up the structure of a Rails
132
+ application. Most of the work in this tutorial will happen in the `app/` folder, but here's a basic rundown on the function of each of the files and folders that Rails created by default:
133
+
134
+ | File/Folder | Purpose |
135
+ | ----------- | ------- |
136
+ |app/|Contains the controllers, models, views, helpers, mailers and assets for your application. You'll focus on this folder for the remainder of this guide.|
137
+ |bin/|Contains the rails script that starts your app and can contain other scripts you use to deploy or run your application.|
138
+ |config/|Configure your application's runtime rules, routes, database, and more. This is covered in more detail in [Configuring Rails Applications](configuring.html)|
139
+ |config.ru|Rack configuration for Rack based servers used to start the application.|
140
+ |db/|Contains your current database schema, as well as the database migrations.|
141
+ |Gemfile<br />Gemfile.lock|These files allow you to specify what gem dependencies are needed for your Rails application. These files are used by the Bundler gem. For more information about Bundler, see [the Bundler website](http://gembundler.com) |
142
+ |lib/|Extended modules for your application.|
143
+ |log/|Application log files.|
144
+ |public/|The only folder seen to the world as-is. Contains the static files and compiled assets.|
145
+ |Rakefile|This file locates and loads tasks that can be run from the command line. The task definitions are defined throughout the components of Rails. Rather than changing Rakefile, you should add your own tasks by adding files to the lib/tasks directory of your application.|
146
+ |README.rdoc|This is a brief instruction manual for your application. You should edit this file to tell others what your application does, how to set it up, and so on.|
147
+ |test/|Unit tests, fixtures, and other test apparatus. These are covered in [Testing Rails Applications](testing.html)|
148
+ |tmp/|Temporary files (like cache, pid and session files)|
149
+ |vendor/|A place for all third-party code. In a typical Rails application, this includes Ruby Gems and the Rails source code (if you optionally install it into your project).|
150
+
151
+ Hello, Rails!
152
+ -------------
153
+
154
+ To begin with, let's get some text up on screen quickly. To do this, you need to get your Rails application server running.
155
+
156
+ ### Starting up the Web Server
157
+
158
+ You actually have a functional Rails application already. To see it, you need to start a web server on your development machine. You can do this by running:
159
+
160
+ ```bash
161
+ $ rails server
162
+ ```
163
+
164
+ TIP: Compiling CoffeeScript to JavaScript requires a JavaScript runtime and the absence of a runtime will give you an `execjs` error. Usually Mac OS X and Windows come with a JavaScript runtime installed. Rails adds the `therubyracer` gem to Gemfile in a commented line for new apps and you can uncomment if you need it. `therubyrhino` is the recommended runtime for JRuby users and is added by default to Gemfile in apps generated under JRuby. You can investigate about all the supported runtimes at [ExecJS](https://github.com/sstephenson/execjs#readme).
165
+
166
+ This will fire up WEBrick, a webserver built into Ruby by default. To see your application in action, open a browser window and navigate to <http://localhost:3000>. You should see the Rails default information page:
167
+
168
+ ![Welcome Aboard screenshot](images/rails_welcome.png)
169
+
170
+ TIP: To stop the web server, hit Ctrl+C in the terminal window where it's running. To verify the server has stopped you should see your command prompt cursor again. For most UNIX-like systems including Mac OS X this will be a dollar sign `$`. In development mode, Rails does not generally require you to restart the server; changes you make in files will be automatically picked up by the server.
171
+
172
+ The "Welcome Aboard" page is the _smoke test_ for a new Rails application: it makes sure that you have your software configured correctly enough to serve a page. You can also click on the _About your application’s environment_ link to see a summary of your application's environment.
173
+
174
+ ### Say "Hello", Rails
175
+
176
+ To get Rails saying "Hello", you need to create at minimum a _controller_ and a _view_.
177
+
178
+ A controller's purpose is to receive specific requests for the application. _Routing_ decides which controller receives which requests. Often, there is more than one route to each controller, and different routes can be served by different _actions_. Each action's purpose is to collect information to provide it to a view.
179
+
180
+ A view's purpose is to display this information in a human readable format. An important distinction to make is that it is the _controller_, not the view, where information is collected. The view should just display that information. By default, view templates are written in a language called ERB (Embedded Ruby) which is converted by the request cycle in Rails before being sent to the user.
181
+
182
+ To create a new controller, you will need to run the "controller" generator and tell it you want a controller called "welcome" with an action called "index", just like this:
183
+
184
+ ```bash
185
+ $ rails generate controller welcome index
186
+ ```
187
+
188
+ Rails will create several files and a route for you.
189
+
190
+ ```bash
191
+ create app/controllers/welcome_controller.rb
192
+ route get "welcome/index"
193
+ invoke erb
194
+ create app/views/welcome
195
+ create app/views/welcome/index.html.erb
196
+ invoke test_unit
197
+ create test/controllers/welcome_controller_test.rb
198
+ invoke helper
199
+ create app/helpers/welcome_helper.rb
200
+ invoke test_unit
201
+ create test/helpers/welcome_helper_test.rb
202
+ invoke assets
203
+ invoke coffee
204
+ create app/assets/javascripts/welcome.js.coffee
205
+ invoke scss
206
+ create app/assets/stylesheets/welcome.css.scss
207
+ ```
208
+
209
+ Most important of these are of course the controller, located at `app/controllers/welcome_controller.rb` and the view, located at `app/views/welcome/index.html.erb`.
210
+
211
+ Open the `app/views/welcome/index.html.erb` file in your text editor and edit it to contain a single line of code:
212
+
213
+ ```html
214
+ <h1>Hello, Rails!</h1>
215
+ ```
216
+
217
+ ### Setting the Application Home Page
218
+
219
+ Now that we have made the controller and view, we need to tell Rails when we want Hello Rails! to show up. In our case, we want it to show up when we navigate to the root URL of our site, <http://localhost:3000>. At the moment, "Welcome Aboard" is occupying that spot.
220
+
221
+ Next, you have to tell Rails where your actual home page is located.
222
+
223
+ Open the file `config/routes.rb` in your editor.
224
+
225
+ ```ruby
226
+ Blog::Application.routes.draw do
227
+ get "welcome/index"
228
+
229
+ # The priority is based upon order of creation:
230
+ # first created -> highest priority.
231
+ # ...
232
+ # You can have the root of your site routed with "root"
233
+ # root to: "welcome#index"
234
+ ```
235
+
236
+ This is your application's _routing file_ which holds entries in a special DSL (domain-specific language) that tells Rails how to connect incoming requests to controllers and actions. This file contains many sample routes on commented lines, and one of them actually shows you how to connect the root of your site to a specific controller and action. Find the line beginning with `root :to` and uncomment it. It should look something like the following:
237
+
238
+ ```ruby
239
+ root to: "welcome#index"
240
+ ```
241
+
242
+ The `root to: "welcome#index"` tells Rails to map requests to the root of the application to the welcome controller's index action and `get "welcome/index"` tells Rails to map requests to <http://localhost:3000/welcome/index> to the welcome controller's index action. This was created earlier when you ran the controller generator (`rails generate controller welcome index`).
243
+
244
+ If you navigate to <http://localhost:3000> in your browser, you'll see the `Hello, Rails!` message you put into `app/views/welcome/index.html.erb`, indicating that this new route is indeed going to `WelcomeController`'s `index` action and is rendering the view correctly.
245
+
246
+ TIP: For more information about routing, refer to [Rails Routing from the Outside In](routing.html).
247
+
248
+ Getting Up and Running
249
+ ----------------------
250
+
251
+ Now that you've seen how to create a controller, an action and a view, let's create something with a bit more substance.
252
+
253
+ In the Blog application, you will now create a new _resource_. A resource is the term used for a collection of similar objects, such as posts, people or animals. You can create, read, update and destroy items for a resource and these operations are referred to as _CRUD_ operations.
254
+
255
+ In the next section, you will add the ability to create new posts in your application and be able to view them. This is the "C" and the "R" from CRUD: creation and reading. The form for doing this will look like this:
256
+
257
+ ![The new post form](images/getting_started/new_post.png)
258
+
259
+ It will look a little basic for now, but that's ok. We'll look at improving the styling for it afterwards.
260
+
261
+ ### Laying down the ground work
262
+
263
+ The first thing that you are going to need to create a new post within the application is a place to do that. A great place for that would be at `/posts/new`. If you attempt to navigate to that now — by visiting <http://localhost:3000/posts/new> — Rails will give you a routing error:
264
+
265
+ ![A routing error, no route matches /posts/new](images/getting_started/routing_error_no_route_matches.png)
266
+
267
+ This is because there is nowhere inside the routes for the application — defined inside `config/routes.rb` — that defines this route. By default, Rails has no routes configured at all, besides the root route you defined earlier, and so you must define your routes as you need them.
268
+
269
+ To do this, you're going to need to create a route inside `config/routes.rb` file, on a new line between the `do` and the `end` for the `draw` method:
270
+
271
+ ```ruby
272
+ get "posts/new"
273
+ ```
274
+
275
+ This route is a super-simple route: it defines a new route that only responds to `GET` requests, and that the route is at `posts/new`. But how does it know where to go without the use of the `:to` option? Well, Rails uses a sensible default here: Rails will assume that you want this route to go to the new action inside the posts controller.
276
+
277
+ With the route defined, requests can now be made to `/posts/new` in the application. Navigate to <http://localhost:3000/posts/new> and you'll see another routing error:
278
+
279
+ ![Another routing error, uninitialized constant PostsController](images/getting_started/routing_error_no_controller.png)
280
+
281
+ This error is happening because this route need a controller to be defined. The route is attempting to find that controller so it can serve the request, but with the controller undefined, it just can't do that. The solution to this particular problem is simple: you need to create a controller called `PostsController`. You can do this by running this command:
282
+
283
+ ```bash
284
+ $ rails g controller posts
285
+ ```
286
+
287
+ If you open up the newly generated `app/controllers/posts_controller.rb` you'll see a fairly empty controller:
288
+
289
+ ```ruby
290
+ class PostsController < ApplicationController
291
+ end
292
+ ```
293
+
294
+ A controller is simply a class that is defined to inherit from `ApplicationController`. It's inside this class that you'll define methods that will become the actions for this controller. These actions will perform CRUD operations on the posts within our system.
295
+
296
+ If you refresh <http://localhost:3000/posts/new> now, you'll get a new error:
297
+
298
+ ![Unknown action new for PostsController!](images/getting_started/unknown_action_new_for_posts.png)
299
+
300
+ This error indicates that Rails cannot find the `new` action inside the `PostsController` that you just generated. This is because when controllers are generated in Rails they are empty by default, unless you tell it you wanted actions during the generation process.
301
+
302
+ To manually define an action inside a controller, all you need to do is to define a new method inside the controller. Open `app/controllers/posts_controller.rb` and inside the `PostsController` class, define a `new` method like this:
303
+
304
+ ```ruby
305
+ def new
306
+ end
307
+ ```
308
+
309
+ With the `new` method defined in `PostsController`, if you refresh <http://localhost:3000/posts/new> you'll see another error:
310
+
311
+ ![Template is missing for posts/new](images/getting_started/template_is_missing_posts_new.png)
312
+
313
+ You're getting this error now because Rails expects plain actions like this one to have views associated with them to display their information. With no view available, Rails errors out.
314
+
315
+ In the above image, the bottom line has been truncated. Let's see what the full thing looks like:
316
+
317
+ <blockquote>
318
+ Missing template posts/new, application/new with {locale:[:en], formats:[:html], handlers:[:erb, :builder, :coffee]}. Searched in: * "/path/to/blog/app/views"
319
+ </blockquote>
320
+
321
+ That's quite a lot of text! Let's quickly go through and understand what each part of it does.
322
+
323
+ The first part identifies what template is missing. In this case, it's the `posts/new` template. Rails will first look for this template. If not found, then it will attempt to load a template called `application/new`. It looks for one here because the `PostsController` inherits from `ApplicationController`.
324
+
325
+ The next part of the message contains a hash. The `:locale` key in this hash simply indicates what spoken language template should be retrieved. By default, this is the English — or "en" — template. The next key, `:formats` specifies the format of template to be served in response. The default format is `:html`, and so Rails is looking for an HTML template. The final key, `:handlers`, is telling us what _template handlers_ could be used to render our template. `:erb` is most commonly used for HTML templates, `:builder` is used for XML templates, and `:coffee` uses CoffeeScript to build JavaScript templates.
326
+
327
+ The final part of this message tells us where Rails has looked for the templates. Templates within a basic Rails application like this are kept in a single location, but in more complex applications it could be many different paths.
328
+
329
+ The simplest template that would work in this case would be one located at `app/views/posts/new.html.erb`. The extension of this file name is key: the first extension is the _format_ of the template, and the second extension is the _handler_ that will be used. Rails is attempting to find a template called `posts/new` within `app/views` for the application. The format for this template can only be `html` and the handler must be one of `erb`, `builder` or `coffee`. Because you want to create a new HTML form, you will be using the `ERB` language. Therefore the file should be called `posts/new.html.erb` and needs to be located inside the `app/views` directory of the application.
330
+
331
+ Go ahead now and create a new file at `app/views/posts/new.html.erb` and write this content in it:
332
+
333
+ ```html
334
+ <h1>New Post</h1>
335
+ ```
336
+
337
+ When you refresh <http://localhost:3000/posts/new> you'll now see that the page has a title. The route, controller, action and view are now working harmoniously! It's time to create the form for a new post.
338
+
339
+ ### The first form
340
+
341
+ To create a form within this template, you will use a <em>form
342
+ builder</em>. The primary form builder for Rails is provided by a helper
343
+ method called `form_for`. To use this method, add this code into `app/views/posts/new.html.erb`:
344
+
345
+ ```html+erb
346
+ <%= form_for :post do |f| %>
347
+ <p>
348
+ <%= f.label :title %><br>
349
+ <%= f.text_field :title %>
350
+ </p>
351
+
352
+ <p>
353
+ <%= f.label :text %><br>
354
+ <%= f.text_area :text %>
355
+ </p>
356
+
357
+ <p>
358
+ <%= f.submit %>
359
+ </p>
360
+ <% end %>
361
+ ```
362
+
363
+ If you refresh the page now, you'll see the exact same form as in the example. Building forms in Rails is really just that easy!
364
+
365
+ When you call `form_for`, you pass it an identifying object for this
366
+ form. In this case, it's the symbol `:post`. This tells the `form_for`
367
+ helper what this form is for. Inside the block for this method, the
368
+ `FormBuilder` object — represented by `f` — is used to build two labels and two text fields, one each for the title and text of a post. Finally, a call to `submit` on the `f` object will create a submit button for the form.
369
+
370
+ There's one problem with this form though. If you inspect the HTML that is generated, by viewing the source of the page, you will see that the `action` attribute for the form is pointing at `/posts/new`. This is a problem because this route goes to the very page that you're on right at the moment, and that route should only be used to display the form for a new post.
371
+
372
+ The form needs to use a different URL in order to go somewhere else.
373
+ This can be done quite simply with the `:url` option of `form_for`.
374
+ Typically in Rails, the action that is used for new form submissions
375
+ like this is called "create", and so the form should be pointed to that action.
376
+
377
+ Edit the `form_for` line inside `app/views/posts/new.html.erb` to look like this:
378
+
379
+ ```html+erb
380
+ <%= form_for :post, url: { action: :create } do |f| %>
381
+ ```
382
+
383
+ In this example, a `Hash` object is passed to the `:url` option. What Rails will do with this is that it will point the form to the `create` action of the current controller, the `PostsController`, and will send a `POST` request to that route. For this to work, you will need to add a route to `config/routes.rb`, right underneath the one for "posts/new":
384
+
385
+ ```ruby
386
+ post "posts" => "posts#create"
387
+ ```
388
+
389
+ By using the `post` method rather than the `get` method, Rails will define a route that will only respond to POST methods. The POST method is the typical method used by forms all over the web.
390
+
391
+ With the form and its associated route defined, you will be able to fill in the form and then click the submit button to begin the process of creating a new post, so go ahead and do that. When you submit the form, you should see a familiar error:
392
+
393
+ ![Unknown action create for PostsController](images/getting_started/unknown_action_create_for_posts.png)
394
+
395
+ You now need to create the `create` action within the `PostsController` for this to work.
396
+
397
+ ### Creating posts
398
+
399
+ To make the "Unknown action" go away, you can define a `create` action within the `PostsController` class in `app/controllers/posts_controller.rb`, underneath the `new` action:
400
+
401
+ ```ruby
402
+ class PostsController < ApplicationController
403
+ def new
404
+ end
405
+
406
+ def create
407
+ end
408
+ end
409
+ ```
410
+
411
+ If you re-submit the form now, you'll see another familiar error: a template is missing. That's ok, we can ignore that for now. What the `create` action should be doing is saving our new post to a database.
412
+
413
+ When a form is submitted, the fields of the form are sent to Rails as _parameters_. These parameters can then be referenced inside the controller actions, typically to perform a particular task. To see what these parameters look like, change the `create` action to this:
414
+
415
+ ```ruby
416
+ def create
417
+ render text: params[:post].inspect
418
+ end
419
+ ```
420
+
421
+ The `render` method here is taking a very simple hash with a key of `text` and value of `params[:post].inspect`. The `params` method is the object which represents the parameters (or fields) coming in from the form. The `params` method returns an `ActiveSupport::HashWithIndifferentAccess` object, which allows you to access the keys of the hash using either strings or symbols. In this situation, the only parameters that matter are the ones from the form.
422
+
423
+ If you re-submit the form one more time you'll now no longer get the missing template error. Instead, you'll see something that looks like the following:
424
+
425
+ ```ruby
426
+ {"title"=>"First post!", "text"=>"This is my first post."}
427
+ ```
428
+
429
+ This action is now displaying the parameters for the post that are coming in from the form. However, this isn't really all that helpful. Yes, you can see the parameters but nothing in particular is being done with them.
430
+
431
+ ### Creating the Post model
432
+
433
+ Models in Rails use a singular name, and their corresponding database tables use
434
+ a plural name. Rails provides a generator for creating models, which
435
+ most Rails developers tend to use when creating new models.
436
+ To create the new model, run this command in your terminal:
437
+
438
+ ```bash
439
+ $ rails generate model Post title:string text:text
440
+ ```
441
+
442
+ With that command we told Rails that we want a `Post` model, together
443
+ with a _title_ attribute of type string, and a _text_ attribute
444
+ of type text. Those attributes are automatically added to the `posts`
445
+ table in the database and mapped to the `Post` model.
446
+
447
+ Rails responded by creating a bunch of files. For
448
+ now, we're only interested in `app/models/post.rb` and
449
+ `db/migrate/20120419084633_create_posts.rb` (your name could be a bit
450
+ different). The latter is responsible
451
+ for creating the database structure, which is what we'll look at next.
452
+
453
+ TIP: Active Record is smart enough to automatically map column names to
454
+ model attributes, which means you don't have to declare attributes
455
+ inside Rails models, as that will be done automatically by Active
456
+ Record.
457
+
458
+ ### Running a Migration
459
+
460
+ As we've just seen, `rails generate model` created a _database
461
+ migration_ file inside the `db/migrate` directory.
462
+ Migrations are Ruby classes that are designed to make it simple to
463
+ create and modify database tables. Rails uses rake commands to run migrations,
464
+ and it's possible to undo a migration after it's been applied to your database.
465
+ Migration filenames include a timestamp to ensure that they're processed in the
466
+ order that they were created.
467
+
468
+ If you look in the `db/migrate/20120419084633_create_posts.rb` file (remember,
469
+ yours will have a slightly different name), here's what you'll find:
470
+
471
+ ```ruby
472
+ class CreatePosts < ActiveRecord::Migration
473
+ def change
474
+ create_table :posts do |t|
475
+ t.string :title
476
+ t.text :text
477
+
478
+ t.timestamps
479
+ end
480
+ end
481
+ end
482
+ ```
483
+
484
+ The above migration creates a method named `change` which will be called when you
485
+ run this migration. The action defined in this method is also reversible, which
486
+ means Rails knows how to reverse the change made by this migration, in case you
487
+ want to reverse it later. When you run this migration it will create a
488
+ `posts` table with one string column and a text column. It also creates two
489
+ timestamp fields to allow Rails to track post creation and update times.
490
+
491
+ TIP: For more information about migrations, refer to [Rails Database
492
+ Migrations](migrations.html).
493
+
494
+ At this point, you can use a rake command to run the migration:
495
+
496
+ ```bash
497
+ $ rake db:migrate
498
+ ```
499
+
500
+ Rails will execute this migration command and tell you it created the Posts
501
+ table.
502
+
503
+ ```bash
504
+ == CreatePosts: migrating ====================================================
505
+ -- create_table(:posts)
506
+ -> 0.0019s
507
+ == CreatePosts: migrated (0.0020s) ===========================================
508
+ ```
509
+
510
+ NOTE. Because you're working in the development environment by default, this
511
+ command will apply to the database defined in the `development` section of your
512
+ `config/database.yml` file. If you would like to execute migrations in another
513
+ environment, for instance in production, you must explicitly pass it when
514
+ invoking the command: `rake db:migrate RAILS_ENV=production`.
515
+
516
+ ### Saving data in the controller
517
+
518
+ Back in `posts_controller`, we need to change the `create` action
519
+ to use the new `Post` model to save the data in the database. Open `app/controllers/posts_controller.rb`
520
+ and change the `create` action to look like this:
521
+
522
+ ```ruby
523
+ def create
524
+ @post = Post.new(params[:post])
525
+
526
+ @post.save
527
+ redirect_to action: :show, id: @post.id
528
+ end
529
+ ```
530
+
531
+ Here's what's going on: every Rails model can be initialized with its
532
+ respective attributes, which are automatically mapped to the respective
533
+ database columns. In the first line we do just that (remember that
534
+ `params[:post]` contains the attributes we're interested in). Then,
535
+ `@post.save` is responsible for saving the model in the database.
536
+ Finally, we redirect the user to the `show` action,
537
+ which we'll define later.
538
+
539
+ TIP: As we'll see later, `@post.save` returns a boolean indicating
540
+ whether the model was saved or not.
541
+
542
+ ### Showing Posts
543
+
544
+ If you submit the form again now, Rails will complain about not finding
545
+ the `show` action. That's not very useful though, so let's add the
546
+ `show` action before proceeding. Open `config/routes.rb` and add the following route:
547
+
548
+ ```ruby
549
+ get "posts/:id" => "posts#show"
550
+ ```
551
+
552
+ The special syntax `:id` tells rails that this route expects an `:id`
553
+ parameter, which in our case will be the id of the post. Note that this
554
+ time we had to specify the actual mapping, `posts#show` because
555
+ otherwise Rails would not know which action to render.
556
+
557
+ As we did before, we need to add the `show` action in
558
+ `app/controllers/posts_controller.rb` and its respective view.
559
+
560
+ ```ruby
561
+ def show
562
+ @post = Post.find(params[:id])
563
+ end
564
+ ```
565
+
566
+ A couple of things to note. We use `Post.find` to find the post we're
567
+ interested in. We also use an instance variable (prefixed by `@`) to
568
+ hold a reference to the post object. We do this because Rails will pass all instance
569
+ variables to the view.
570
+
571
+ Now, create a new file `app/view/posts/show.html.erb` with the following
572
+ content:
573
+
574
+ ```html+erb
575
+ <p>
576
+ <strong>Title:</strong>
577
+ <%= @post.title %>
578
+ </p>
579
+
580
+ <p>
581
+ <strong>Text:</strong>
582
+ <%= @post.text %>
583
+ </p>
584
+ ```
585
+
586
+ If you now go to
587
+ <http://localhost:3000/posts/new> you'll *almost* be able to create a post. Try
588
+ it! You should get an error that looks like this:
589
+
590
+ ![Forbidden attributes for new post](images/getting_started/forbidden_attributes_for_new_post.png)
591
+
592
+ Rails has several security features that help you write secure applications,
593
+ and you're running into one of them now. This one is called
594
+ 'strong_parameters,' which requires us to tell Rails exactly which parameters
595
+ we want to accept in our controllers. In this case, we want to allow the
596
+ 'title' and 'text' parameters, so change your `create` controller action to
597
+ look like this:
598
+
599
+ ```
600
+ def create
601
+ @post = Post.new(params[:post].permit(:title, :text))
602
+
603
+ @post.save
604
+ redirect_to action: :show, id: @post.id
605
+ end
606
+ ```
607
+
608
+ See the `permit`? It allows us to accept both `title` and `text` in this
609
+ action. With this change, you should finally be able to create new `Post`s.
610
+ Visit <http://localhost:3000/posts/new> and give it a try!
611
+
612
+ ![Show action for posts](images/getting_started/show_action_for_posts.png)
613
+
614
+ ### Listing all posts
615
+
616
+ We still need a way to list all our posts, so let's do that. As usual,
617
+ we'll need a route placed into `config/routes.rb`:
618
+
619
+ ```ruby
620
+ get "posts" => "posts#index"
621
+ ```
622
+
623
+ And an action for that route inside the `PostsController` in the `app/controllers/posts_controller.rb` file:
624
+
625
+ ```ruby
626
+ def index
627
+ @posts = Post.all
628
+ end
629
+ ```
630
+
631
+ And then finally a view for this action, located at `app/views/posts/index.html.erb`:
632
+
633
+ ```html+erb
634
+ <h1>Listing posts</h1>
635
+
636
+ <table>
637
+ <tr>
638
+ <th>Title</th>
639
+ <th>Text</th>
640
+ </tr>
641
+
642
+ <% @posts.each do |post| %>
643
+ <tr>
644
+ <td><%= post.title %></td>
645
+ <td><%= post.text %></td>
646
+ </tr>
647
+ <% end %>
648
+ </table>
649
+ ```
650
+
651
+ Now if you go to `http://localhost:3000/posts` you will see a list of all the posts that you have created.
652
+
653
+ ### Adding links
654
+
655
+ You can now create, show, and list posts. Now let's add some links to
656
+ navigate through pages.
657
+
658
+ Open `app/views/welcome/index.html.erb` and modify it as follows:
659
+
660
+ ```html+erb
661
+ <h1>Hello, Rails!</h1>
662
+ <%= link_to "My Blog", controller: "posts" %>
663
+ ```
664
+
665
+ The `link_to` method is one of Rails' built-in view helpers. It creates a
666
+ hyperlink based on text to display and where to go - in this case, to the path
667
+ for posts.
668
+
669
+ Let's add links to the other views as well, starting with adding this "New Post" link to `app/views/posts/index.html.erb`, placing it above the `<table>` tag:
670
+
671
+ ```erb
672
+ <%= link_to 'New post', action: :new %>
673
+ ```
674
+
675
+ This link will allow you to bring up the form that lets you create a new post. You should also add a link to this template — `app/views/posts/new.html.erb` — to go back to the `index` action. Do this by adding this underneath the form in this template:
676
+
677
+ ```erb
678
+ <%= form_for :post do |f| %>
679
+ ...
680
+ <% end %>
681
+
682
+ <%= link_to 'Back', action: :index %>
683
+ ```
684
+
685
+ Finally, add another link to the `app/views/posts/show.html.erb` template to go back to the `index` action as well, so that people who are viewing a single post can go back and view the whole list again:
686
+
687
+ ```html+erb
688
+ <p>
689
+ <strong>Title:</strong>
690
+ <%= @post.title %>
691
+ </p>
692
+
693
+ <p>
694
+ <strong>Text:</strong>
695
+ <%= @post.text %>
696
+ </p>
697
+
698
+ <%= link_to 'Back', action: :index %>
699
+ ```
700
+
701
+ TIP: If you want to link to an action in the same controller, you don't
702
+ need to specify the `:controller` option, as Rails will use the current
703
+ controller by default.
704
+
705
+ TIP: In development mode (which is what you're working in by default), Rails
706
+ reloads your application with every browser request, so there's no need to stop
707
+ and restart the web server when a change is made.
708
+
709
+ ### Allowing the update of fields
710
+
711
+ The model file, `app/models/post.rb` is about as simple as it can get:
712
+
713
+ ```ruby
714
+ class Post < ActiveRecord::Base
715
+ end
716
+ ```
717
+
718
+ There isn't much to this file - but note that the `Post` class inherits from
719
+ `ActiveRecord::Base`. Active Record supplies a great deal of functionality to
720
+ your Rails models for free, including basic database CRUD (Create, Read, Update,
721
+ Destroy) operations, data validation, as well as sophisticated search support
722
+ and the ability to relate multiple models to one another.
723
+
724
+ ### Adding Some Validation
725
+
726
+ Rails includes methods to help you validate the data that you send to models.
727
+ Open the `app/models/post.rb` file and edit it:
728
+
729
+ ```ruby
730
+ class Post < ActiveRecord::Base
731
+ validates :title, presence: true,
732
+ length: { minimum: 5 }
733
+ end
734
+ ```
735
+
736
+ These changes will ensure that all posts have a title that is at least five
737
+ characters long. Rails can validate a variety of conditions in a model,
738
+ including the presence or uniqueness of columns, their format, and the
739
+ existence of associated objects. Validations are covered in detail in [Active
740
+ Record Validations](active_record_validations.html)
741
+
742
+ With the validation now in place, when you call `@post.save` on an invalid
743
+ post, it will return `false`. If you open `app/controllers/posts_controller.rb`
744
+ again, you'll notice that we don't check the result of calling `@post.save`
745
+ inside the `create` action. If `@post.save` fails in this situation, we need to
746
+ show the form back to the user. To do this, change the `new` and `create`
747
+ actions inside `app/controllers/posts_controller.rb` to these:
748
+
749
+ ```ruby
750
+ def new
751
+ @post = Post.new
752
+ end
753
+
754
+ def create
755
+ @post = Post.new(params[:post].permit(:title, :text))
756
+
757
+ if @post.save
758
+ redirect_to action: :show, id: @post.id
759
+ else
760
+ render 'new'
761
+ end
762
+ end
763
+ ```
764
+
765
+ The `new` action is now creating a new instance variable called `@post`, and
766
+ you'll see why that is in just a few moments.
767
+
768
+ Notice that inside the `create` action we use `render` instead of `redirect_to` when `save`
769
+ returns `false`. The `render` method is used so that the `@post` object is passed back to the `new` template when it is rendered. This rendering is done within the same request as the form submission, whereas the `redirect_to` will tell the browser to issue another request.
770
+
771
+ If you reload
772
+ <http://localhost:3000/posts/new> and
773
+ try to save a post without a title, Rails will send you back to the
774
+ form, but that's not very useful. You need to tell the user that
775
+ something went wrong. To do that, you'll modify
776
+ `app/views/posts/new.html.erb` to check for error messages:
777
+
778
+ ```html+erb
779
+ <%= form_for :post, url: { action: :create } do |f| %>
780
+ <% if @post.errors.any? %>
781
+ <div id="errorExplanation">
782
+ <h2><%= pluralize(@post.errors.count, "error") %> prohibited
783
+ this post from being saved:</h2>
784
+ <ul>
785
+ <% @post.errors.full_messages.each do |msg| %>
786
+ <li><%= msg %></li>
787
+ <% end %>
788
+ </ul>
789
+ </div>
790
+ <% end %>
791
+ <p>
792
+ <%= f.label :title %><br>
793
+ <%= f.text_field :title %>
794
+ </p>
795
+
796
+ <p>
797
+ <%= f.label :text %><br>
798
+ <%= f.text_area :text %>
799
+ </p>
800
+
801
+ <p>
802
+ <%= f.submit %>
803
+ </p>
804
+ <% end %>
805
+
806
+ <%= link_to 'Back', action: :index %>
807
+ ```
808
+
809
+ A few things are going on. We check if there are any errors with
810
+ `@post.errors.any?`, and in that case we show a list of all
811
+ errors with `@post.errors.full_messages`.
812
+
813
+ `pluralize` is a rails helper that takes a number and a string as its
814
+ arguments. If the number is greater than one, the string will be automatically pluralized.
815
+
816
+ The reason why we added `@post = Post.new` in `posts_controller` is that
817
+ otherwise `@post` would be `nil` in our view, and calling
818
+ `@post.errors.any?` would throw an error.
819
+
820
+ TIP: Rails automatically wraps fields that contain an error with a div
821
+ with class `field_with_errors`. You can define a css rule to make them
822
+ standout.
823
+
824
+ Now you'll get a nice error message when saving a post without title when you
825
+ attempt to do just that on the new post form [(http://localhost:3000/posts/new)](http://localhost:3000/posts/new).
826
+
827
+ ![Form With Errors](images/getting_started/form_with_errors.png)
828
+
829
+ ### Updating Posts
830
+
831
+ We've covered the "CR" part of CRUD. Now let's focus on the "U" part, updating posts.
832
+
833
+ The first step we'll take is adding an `edit` action to `posts_controller`.
834
+
835
+ Start by adding a route to `config/routes.rb`:
836
+
837
+ ```ruby
838
+ get "posts/:id/edit" => "posts#edit"
839
+ ```
840
+
841
+ And then add the controller action:
842
+
843
+ ```ruby
844
+ def edit
845
+ @post = Post.find(params[:id])
846
+ end
847
+ ```
848
+
849
+ The view will contain a form similar to the one we used when creating
850
+ new posts. Create a file called `app/views/posts/edit.html.erb` and make
851
+ it look as follows:
852
+
853
+ ```html+erb
854
+ <h1>Editing post</h1>
855
+
856
+ <%= form_for :post, url: { action: :update, id: @post.id },
857
+ method: :patch do |f| %>
858
+ <% if @post.errors.any? %>
859
+ <div id="errorExplanation">
860
+ <h2><%= pluralize(@post.errors.count, "error") %> prohibited
861
+ this post from being saved:</h2>
862
+ <ul>
863
+ <% @post.errors.full_messages.each do |msg| %>
864
+ <li><%= msg %></li>
865
+ <% end %>
866
+ </ul>
867
+ </div>
868
+ <% end %>
869
+ <p>
870
+ <%= f.label :title %><br>
871
+ <%= f.text_field :title %>
872
+ </p>
873
+
874
+ <p>
875
+ <%= f.label :text %><br>
876
+ <%= f.text_area :text %>
877
+ </p>
878
+
879
+ <p>
880
+ <%= f.submit %>
881
+ </p>
882
+ <% end %>
883
+
884
+ <%= link_to 'Back', action: :index %>
885
+ ```
886
+
887
+ This time we point the form to the `update` action, which is not defined yet
888
+ but will be very soon.
889
+
890
+ The `method: :patch` option tells Rails that we want this form to be submitted
891
+ via the `PATCH` HTTP method which is the HTTP method you're expected to use to
892
+ **update** resources according to the REST protocol.
893
+
894
+ TIP: By default forms built with the _form_for_ helper are sent via `POST`.
895
+
896
+ Next, we need to add the `update` action. The file
897
+ `config/routes.rb` will need just one more line:
898
+
899
+ ```ruby
900
+ patch "posts/:id" => "posts#update"
901
+ ```
902
+
903
+ And then create the `update` action in `app/controllers/posts_controller.rb`:
904
+
905
+ ```ruby
906
+ def update
907
+ @post = Post.find(params[:id])
908
+
909
+ if @post.update(params[:post].permit(:title, :text))
910
+ redirect_to action: :show, id: @post.id
911
+ else
912
+ render 'edit'
913
+ end
914
+ end
915
+ ```
916
+
917
+ The new method, `update`, is used when you want to update a record
918
+ that already exists, and it accepts a hash containing the attributes
919
+ that you want to update. As before, if there was an error updating the
920
+ post we want to show the form back to the user.
921
+
922
+ TIP: You don't need to pass all attributes to `update`. For
923
+ example, if you'd call `@post.update(title: 'A new title')`
924
+ Rails would only update the `title` attribute, leaving all other
925
+ attributes untouched.
926
+
927
+ Finally, we want to show a link to the `edit` action in the list of all the
928
+ posts, so let's add that now to `app/views/posts/index.html.erb` to make it
929
+ appear next to the "Show" link:
930
+
931
+ ```html+erb
932
+ <table>
933
+ <tr>
934
+ <th>Title</th>
935
+ <th>Text</th>
936
+ <th></th>
937
+ <th></th>
938
+ </tr>
939
+
940
+ <% @posts.each do |post| %>
941
+ <tr>
942
+ <td><%= post.title %></td>
943
+ <td><%= post.text %></td>
944
+ <td><%= link_to 'Show', action: :show, id: post.id %></td>
945
+ <td><%= link_to 'Edit', action: :edit, id: post.id %></td>
946
+ </tr>
947
+ <% end %>
948
+ </table>
949
+ ```
950
+
951
+ And we'll also add one to the `app/views/posts/show.html.erb` template as well,
952
+ so that there's also an "Edit" link on a post's page. Add this at the bottom of
953
+ the template:
954
+
955
+ ```html+erb
956
+ ...
957
+
958
+ <%= link_to 'Back', action: :index %>
959
+ | <%= link_to 'Edit', action: :edit, id: @post.id %>
960
+ ```
961
+
962
+ And here's how our app looks so far:
963
+
964
+ ![Index action with edit link](images/getting_started/index_action_with_edit_link.png)
965
+
966
+ ### Using partials to clean up duplication in views
967
+
968
+ Our `edit` page looks very similar to the `new` page, in fact they
969
+ both share the same code for displaying the form. Let's remove some duplication
970
+ by using a view partial. By convention, partial files are prefixed by an
971
+ underscore.
972
+
973
+ TIP: You can read more about partials in the
974
+ [Layouts and Rendering in Rails](layouts_and_rendering.html) guide.
975
+
976
+ Create a new file `app/views/posts/_form.html.erb` with the following
977
+ content:
978
+
979
+ ```html+erb
980
+ <%= form_for @post do |f| %>
981
+ <% if @post.errors.any? %>
982
+ <div id="errorExplanation">
983
+ <h2><%= pluralize(@post.errors.count, "error") %> prohibited
984
+ this post from being saved:</h2>
985
+ <ul>
986
+ <% @post.errors.full_messages.each do |msg| %>
987
+ <li><%= msg %></li>
988
+ <% end %>
989
+ </ul>
990
+ </div>
991
+ <% end %>
992
+ <p>
993
+ <%= f.label :title %><br>
994
+ <%= f.text_field :title %>
995
+ </p>
996
+
997
+ <p>
998
+ <%= f.label :text %><br>
999
+ <%= f.text_area :text %>
1000
+ </p>
1001
+
1002
+ <p>
1003
+ <%= f.submit %>
1004
+ </p>
1005
+ <% end %>
1006
+ ```
1007
+
1008
+ Everything except for the `form_for` declaration remained the same.
1009
+ How `form_for` can figure out the right `action` and `method` attributes
1010
+ when building the form will be explained in just a moment. For now, let's update the
1011
+ `app/views/posts/new.html.erb` view to use this new partial, rewriting it
1012
+ completely:
1013
+
1014
+ ```html+erb
1015
+ <h1>New post</h1>
1016
+
1017
+ <%= render 'form' %>
1018
+
1019
+ <%= link_to 'Back', action: :index %>
1020
+ ```
1021
+
1022
+ Then do the same for the `app/views/posts/edit.html.erb` view:
1023
+
1024
+ ```html+erb
1025
+ <h1>Edit post</h1>
1026
+
1027
+ <%= render 'form' %>
1028
+
1029
+ <%= link_to 'Back', action: :index %>
1030
+ ```
1031
+
1032
+ Point your browser to <http://localhost:3000/posts/new> and
1033
+ try creating a new post. Everything still works. Now try editing the
1034
+ post and you'll receive the following error:
1035
+
1036
+ ![Undefined method post_path](images/getting_started/undefined_method_post_path.png)
1037
+
1038
+ To understand this error, you need to understand how `form_for` works.
1039
+ When you pass an object to `form_for` and you don't specify a `:url`
1040
+ option, Rails will try to guess the `action` and `method` options by
1041
+ checking if the passed object is a new record or not. Rails follows the
1042
+ REST convention, so to create a new `Post` object it will look for a
1043
+ route named `posts_path`, and to update a `Post` object it will look for
1044
+ a route named `post_path` and pass the current object. Similarly, rails
1045
+ knows that it should create new objects via POST and update them via
1046
+ PUT.
1047
+
1048
+ If you run `rake routes` from the console you'll see that we already
1049
+ have a `posts_path` route, which was created automatically by Rails when we
1050
+ defined the route for the index action.
1051
+ However, we don't have a `post_path` yet, which is the reason why we
1052
+ received an error before. With your server running you can view your routes by visiting [localhost:3000/rails/info/routes](http://localhost:3000/rails/info/routes), or you can generate them from the command line by running `rake routes`:
1053
+
1054
+ ```bash
1055
+ $ rake routes
1056
+
1057
+ posts GET /posts(.:format) posts#index
1058
+ posts_new GET /posts/new(.:format) posts#new
1059
+ POST /posts(.:format) posts#create
1060
+ GET /posts/:id(.:format) posts#show
1061
+ GET /posts/:id/edit(.:format) posts#edit
1062
+ PUT /posts/:id(.:format) posts#update
1063
+ root / welcome#index
1064
+ ```
1065
+
1066
+ To fix this, open `config/routes.rb` and modify the `get "posts/:id"`
1067
+ line like this:
1068
+
1069
+ ```ruby
1070
+ get "posts/:id" => "posts#show", as: :post
1071
+ ```
1072
+
1073
+ The `:as` option tells the `get` method that we want to make routing helpers
1074
+ called `post_url` and `post_path` available to our application. These are
1075
+ precisely the methods that the `form_for` needs when editing a post, and so now
1076
+ you'll be able to update posts again.
1077
+
1078
+ NOTE: The `:as` option is available on the `post`, `patch`, `put`, `delete` and `match`
1079
+ routing methods also.
1080
+
1081
+ ### Deleting Posts
1082
+
1083
+ We're now ready to cover the "D" part of CRUD, deleting posts from the
1084
+ database. Following the REST convention, we're going to add a route for
1085
+ deleting posts to `config/routes.rb`:
1086
+
1087
+ ```ruby
1088
+ delete "posts/:id" => "posts#destroy"
1089
+ ```
1090
+
1091
+ The `delete` routing method should be used for routes that destroy
1092
+ resources. If this was left as a typical `get` route, it could be possible for
1093
+ people to craft malicious URLs like this:
1094
+
1095
+ ```html
1096
+ <a href='http://example.com/posts/1/destroy'>look at this cat!</a>
1097
+ ```
1098
+
1099
+ We use the `delete` method for destroying resources, and this route is mapped to
1100
+ the `destroy` action inside `app/controllers/posts_controller.rb`, which doesn't exist yet, but is
1101
+ provided below:
1102
+
1103
+ ```ruby
1104
+ def destroy
1105
+ @post = Post.find(params[:id])
1106
+ @post.destroy
1107
+
1108
+ redirect_to action: :index
1109
+ end
1110
+ ```
1111
+
1112
+ You can call `destroy` on Active Record objects when you want to delete
1113
+ them from the database. Note that we don't need to add a view for this
1114
+ action since we're redirecting to the `index` action.
1115
+
1116
+ Finally, add a 'destroy' link to your `index` action template
1117
+ (`app/views/posts/index.html.erb`) to wrap everything
1118
+ together.
1119
+
1120
+ ```html+erb
1121
+ <h1>Listing Posts</h1>
1122
+ <table>
1123
+ <tr>
1124
+ <th>Title</th>
1125
+ <th>Text</th>
1126
+ <th></th>
1127
+ <th></th>
1128
+ <th></th>
1129
+ </tr>
1130
+
1131
+ <% @posts.each do |post| %>
1132
+ <tr>
1133
+ <td><%= post.title %></td>
1134
+ <td><%= post.text %></td>
1135
+ <td><%= link_to 'Show', action: :show, id: post.id %></td>
1136
+ <td><%= link_to 'Edit', action: :edit, id: post.id %></td>
1137
+ <td><%= link_to 'Destroy', { action: :destroy, id: post.id },
1138
+ method: :delete, data: { confirm: 'Are you sure?' } %></td>
1139
+ </tr>
1140
+ <% end %>
1141
+ </table>
1142
+ ```
1143
+
1144
+ Here we're using `link_to` in a different way. We wrap the
1145
+ `:action` and `:id` attributes in a hash so that we can pass those two keys in
1146
+ first as one argument, and then the final two keys as another argument. The `:method` and `:'data-confirm'`
1147
+ options are used as HTML5 attributes so that when the link is clicked,
1148
+ Rails will first show a confirm dialog to the user, and then submit the link with method `delete`.
1149
+ This is done via the JavaScript file `jquery_ujs` which is automatically included
1150
+ into your application's layout (`app/views/layouts/application.html.erb`) when you
1151
+ generated the application. Without this file, the confirmation dialog box wouldn't appear.
1152
+
1153
+ ![Confirm Dialog](images/getting_started/confirm_dialog.png)
1154
+
1155
+ Congratulations, you can now create, show, list, update and destroy
1156
+ posts. In the next section will see how Rails can aid us when creating
1157
+ REST applications, and how we can refactor our Blog app to take
1158
+ advantage of it.
1159
+
1160
+ ### Going Deeper into REST
1161
+
1162
+ We've now covered all the CRUD actions of a REST app. We did so by
1163
+ declaring separate routes with the appropriate verbs into
1164
+ `config/routes.rb`. Here's how that file looks so far:
1165
+
1166
+ ```ruby
1167
+ get "posts" => "posts#index"
1168
+ get "posts/new"
1169
+ post "posts" => "posts#create"
1170
+ get "posts/:id" => "posts#show", as: :post
1171
+ get "posts/:id/edit" => "posts#edit"
1172
+ patch "posts/:id" => "posts#update"
1173
+ delete "posts/:id" => "posts#destroy"
1174
+ ```
1175
+
1176
+ That's a lot to type for covering a single **resource**. Fortunately,
1177
+ Rails provides a `resources` method which can be used to declare a
1178
+ standard REST resource. Here's how `config/routes.rb` looks after the
1179
+ cleanup:
1180
+
1181
+ ```ruby
1182
+ Blog::Application.routes.draw do
1183
+
1184
+ resources :posts
1185
+
1186
+ root to: "welcome#index"
1187
+ end
1188
+ ```
1189
+
1190
+ If you run `rake routes`, you'll see that all the routes that we
1191
+ declared before are still available:
1192
+
1193
+ ```bash
1194
+ $ rake routes
1195
+ posts GET /posts(.:format) posts#index
1196
+ POST /posts(.:format) posts#create
1197
+ new_post GET /posts/new(.:format) posts#new
1198
+ edit_post GET /posts/:id/edit(.:format) posts#edit
1199
+ post GET /posts/:id(.:format) posts#show
1200
+ PUT /posts/:id(.:format) posts#update
1201
+ DELETE /posts/:id(.:format) posts#destroy
1202
+ root / welcome#index
1203
+ ```
1204
+
1205
+ Also, if you go through the motions of creating, updating and deleting
1206
+ posts the app still works as before.
1207
+
1208
+ TIP: In general, Rails encourages the use of resources objects in place
1209
+ of declaring routes manually. It was only done in this guide as a learning
1210
+ exercise. For more information about routing, see
1211
+ [Rails Routing from the Outside In](routing.html).
1212
+
1213
+ Adding a Second Model
1214
+ ---------------------
1215
+
1216
+ It's time to add a second model to the application. The second model will handle comments on
1217
+ posts.
1218
+
1219
+ ### Generating a Model
1220
+
1221
+ We're going to see the same generator that we used before when creating
1222
+ the `Post` model. This time we'll create a `Comment` model to hold
1223
+ reference of post comments. Run this command in your terminal:
1224
+
1225
+ ```bash
1226
+ $ rails generate model Comment commenter:string body:text post:references
1227
+ ```
1228
+
1229
+ This command will generate four files:
1230
+
1231
+ | File | Purpose |
1232
+ | -------------------------------------------- | ------------------------------------------------------------------------------------------------------ |
1233
+ | db/migrate/20100207235629_create_comments.rb | Migration to create the comments table in your database (your name will include a different timestamp) |
1234
+ | app/models/comment.rb | The Comment model |
1235
+ | test/models/comment_test.rb | Testing harness for the comments model |
1236
+ | test/fixtures/comments.yml | Sample comments for use in testing |
1237
+
1238
+ First, take a look at `app/models/comment.rb`:
1239
+
1240
+ ```ruby
1241
+ class Comment < ActiveRecord::Base
1242
+ belongs_to :post
1243
+ end
1244
+ ```
1245
+
1246
+ This is very similar to the `post.rb` model that you saw earlier. The difference
1247
+ is the line `belongs_to :post`, which sets up an Active Record _association_.
1248
+ You'll learn a little about associations in the next section of this guide.
1249
+
1250
+ In addition to the model, Rails has also made a migration to create the
1251
+ corresponding database table:
1252
+
1253
+ ```ruby
1254
+ class CreateComments < ActiveRecord::Migration
1255
+ def change
1256
+ create_table :comments do |t|
1257
+ t.string :commenter
1258
+ t.text :body
1259
+ t.references :post
1260
+
1261
+ t.timestamps
1262
+ end
1263
+
1264
+ add_index :comments, :post_id
1265
+ end
1266
+ end
1267
+ ```
1268
+
1269
+ The `t.references` line sets up a foreign key column for the association between
1270
+ the two models. And the `add_index` line sets up an index for this association
1271
+ column. Go ahead and run the migration:
1272
+
1273
+ ```bash
1274
+ $ rake db:migrate
1275
+ ```
1276
+
1277
+ Rails is smart enough to only execute the migrations that have not already been
1278
+ run against the current database, so in this case you will just see:
1279
+
1280
+ ```bash
1281
+ == CreateComments: migrating =================================================
1282
+ -- create_table(:comments)
1283
+ -> 0.0008s
1284
+ -- add_index(:comments, :post_id)
1285
+ -> 0.0003s
1286
+ == CreateComments: migrated (0.0012s) ========================================
1287
+ ```
1288
+
1289
+ ### Associating Models
1290
+
1291
+ Active Record associations let you easily declare the relationship between two
1292
+ models. In the case of comments and posts, you could write out the relationships
1293
+ this way:
1294
+
1295
+ * Each comment belongs to one post.
1296
+ * One post can have many comments.
1297
+
1298
+ In fact, this is very close to the syntax that Rails uses to declare this
1299
+ association. You've already seen the line of code inside the `Comment` model (app/models/comment.rb) that
1300
+ makes each comment belong to a Post:
1301
+
1302
+ ```ruby
1303
+ class Comment < ActiveRecord::Base
1304
+ belongs_to :post
1305
+ end
1306
+ ```
1307
+
1308
+ You'll need to edit `app/models/post.rb` to add the other side of the association:
1309
+
1310
+ ```ruby
1311
+ class Post < ActiveRecord::Base
1312
+ has_many :comments
1313
+ validates :title, presence: true,
1314
+ length: { minimum: 5 }
1315
+ [...]
1316
+ end
1317
+ ```
1318
+
1319
+ These two declarations enable a good bit of automatic behavior. For example, if
1320
+ you have an instance variable `@post` containing a post, you can retrieve all
1321
+ the comments belonging to that post as an array using `@post.comments`.
1322
+
1323
+ TIP: For more information on Active Record associations, see the [Active Record
1324
+ Associations](association_basics.html) guide.
1325
+
1326
+ ### Adding a Route for Comments
1327
+
1328
+ As with the `welcome` controller, we will need to add a route so that Rails knows
1329
+ where we would like to navigate to see `comments`. Open up the
1330
+ `config/routes.rb` file again, and edit it as follows:
1331
+
1332
+ ```ruby
1333
+ resources :posts do
1334
+ resources :comments
1335
+ end
1336
+ ```
1337
+
1338
+ This creates `comments` as a _nested resource_ within `posts`. This is another
1339
+ part of capturing the hierarchical relationship that exists between posts and
1340
+ comments.
1341
+
1342
+ TIP: For more information on routing, see the [Rails Routing](routing.html) guide.
1343
+
1344
+ ### Generating a Controller
1345
+
1346
+ With the model in hand, you can turn your attention to creating a matching
1347
+ controller. Again, we'll use the same generator we used before:
1348
+
1349
+ ```bash
1350
+ $ rails generate controller Comments
1351
+ ```
1352
+
1353
+ This creates six files and one empty directory:
1354
+
1355
+ | File/Directory | Purpose |
1356
+ | -------------------------------------------- | ---------------------------------------- |
1357
+ | app/controllers/comments_controller.rb | The Comments controller |
1358
+ | app/views/comments/ | Views of the controller are stored here |
1359
+ | test/controllers/comments_controller_test.rb | The test for the controller |
1360
+ | app/helpers/comments_helper.rb | A view helper file |
1361
+ | test/helpers/comments_helper_test.rb | The test for the helper |
1362
+ | app/assets/javascripts/comment.js.coffee | CoffeeScript for the controller |
1363
+ | app/assets/stylesheets/comment.css.scss | Cascading style sheet for the controller |
1364
+
1365
+ Like with any blog, our readers will create their comments directly after
1366
+ reading the post, and once they have added their comment, will be sent back to
1367
+ the post show page to see their comment now listed. Due to this, our
1368
+ `CommentsController` is there to provide a method to create comments and delete
1369
+ spam comments when they arrive.
1370
+
1371
+ So first, we'll wire up the Post show template
1372
+ (`app/views/posts/show.html.erb`) to let us make a new comment:
1373
+
1374
+ ```html+erb
1375
+ <p>
1376
+ <strong>Title:</strong>
1377
+ <%= @post.title %>
1378
+ </p>
1379
+
1380
+ <p>
1381
+ <strong>Text:</strong>
1382
+ <%= @post.text %>
1383
+ </p>
1384
+
1385
+ <h2>Add a comment:</h2>
1386
+ <%= form_for([@post, @post.comments.build]) do |f| %>
1387
+ <p>
1388
+ <%= f.label :commenter %><br />
1389
+ <%= f.text_field :commenter %>
1390
+ </p>
1391
+ <p>
1392
+ <%= f.label :body %><br />
1393
+ <%= f.text_area :body %>
1394
+ </p>
1395
+ <p>
1396
+ <%= f.submit %>
1397
+ </p>
1398
+ <% end %>
1399
+
1400
+ <%= link_to 'Edit Post', edit_post_path(@post) %> |
1401
+ <%= link_to 'Back to Posts', posts_path %>
1402
+ ```
1403
+
1404
+ This adds a form on the `Post` show page that creates a new comment by
1405
+ calling the `CommentsController` `create` action. The `form_for` call here uses
1406
+ an array, which will build a nested route, such as `/posts/1/comments`.
1407
+
1408
+ Let's wire up the `create` in `app/controllers/comments_controller.rb`:
1409
+
1410
+ ```ruby
1411
+ class CommentsController < ApplicationController
1412
+ def create
1413
+ @post = Post.find(params[:post_id])
1414
+ @comment = @post.comments.create(params[:comment].permit(:commenter, :body))
1415
+ redirect_to post_path(@post)
1416
+ end
1417
+ end
1418
+ ```
1419
+
1420
+ You'll see a bit more complexity here than you did in the controller for posts.
1421
+ That's a side-effect of the nesting that you've set up. Each request for a
1422
+ comment has to keep track of the post to which the comment is attached, thus the
1423
+ initial call to the `find` method of the `Post` model to get the post in question.
1424
+
1425
+ In addition, the code takes advantage of some of the methods available for an
1426
+ association. We use the `create` method on `@post.comments` to create and save
1427
+ the comment. This will automatically link the comment so that it belongs to that
1428
+ particular post.
1429
+
1430
+ Once we have made the new comment, we send the user back to the original post
1431
+ using the `post_path(@post)` helper. As we have already seen, this calls the
1432
+ `show` action of the `PostsController` which in turn renders the `show.html.erb`
1433
+ template. This is where we want the comment to show, so let's add that to the
1434
+ `app/views/posts/show.html.erb`.
1435
+
1436
+ ```html+erb
1437
+ <p>
1438
+ <strong>Title:</strong>
1439
+ <%= @post.title %>
1440
+ </p>
1441
+
1442
+ <p>
1443
+ <strong>Text:</strong>
1444
+ <%= @post.text %>
1445
+ </p>
1446
+
1447
+ <h2>Comments</h2>
1448
+ <% @post.comments.each do |comment| %>
1449
+ <p>
1450
+ <strong>Commenter:</strong>
1451
+ <%= comment.commenter %>
1452
+ </p>
1453
+
1454
+ <p>
1455
+ <strong>Comment:</strong>
1456
+ <%= comment.body %>
1457
+ </p>
1458
+ <% end %>
1459
+
1460
+ <h2>Add a comment:</h2>
1461
+ <%= form_for([@post, @post.comments.build]) do |f| %>
1462
+ <p>
1463
+ <%= f.label :commenter %><br />
1464
+ <%= f.text_field :commenter %>
1465
+ </p>
1466
+ <p>
1467
+ <%= f.label :body %><br />
1468
+ <%= f.text_area :body %>
1469
+ </p>
1470
+ <p>
1471
+ <%= f.submit %>
1472
+ </p>
1473
+ <% end %>
1474
+
1475
+ <%= link_to 'Edit Post', edit_post_path(@post) %> |
1476
+ <%= link_to 'Back to Posts', posts_path %>
1477
+ ```
1478
+
1479
+ Now you can add posts and comments to your blog and have them show up in the
1480
+ right places.
1481
+
1482
+ ![Post with Comments](images/getting_started/post_with_comments.png)
1483
+
1484
+ Refactoring
1485
+ -----------
1486
+
1487
+ Now that we have posts and comments working, take a look at the
1488
+ `app/views/posts/show.html.erb` template. It is getting long and awkward. We can
1489
+ use partials to clean it up.
1490
+
1491
+ ### Rendering Partial Collections
1492
+
1493
+ First, we will make a comment partial to extract showing all the comments for the
1494
+ post. Create the file `app/views/comments/_comment.html.erb` and put the
1495
+ following into it:
1496
+
1497
+ ```html+erb
1498
+ <p>
1499
+ <strong>Commenter:</strong>
1500
+ <%= comment.commenter %>
1501
+ </p>
1502
+
1503
+ <p>
1504
+ <strong>Comment:</strong>
1505
+ <%= comment.body %>
1506
+ </p>
1507
+ ```
1508
+
1509
+ Then you can change `app/views/posts/show.html.erb` to look like the
1510
+ following:
1511
+
1512
+ ```html+erb
1513
+ <p>
1514
+ <strong>Title:</strong>
1515
+ <%= @post.title %>
1516
+ </p>
1517
+
1518
+ <p>
1519
+ <strong>Text:</strong>
1520
+ <%= @post.text %>
1521
+ </p>
1522
+
1523
+ <h2>Comments</h2>
1524
+ <%= render @post.comments %>
1525
+
1526
+ <h2>Add a comment:</h2>
1527
+ <%= form_for([@post, @post.comments.build]) do |f| %>
1528
+ <p>
1529
+ <%= f.label :commenter %><br />
1530
+ <%= f.text_field :commenter %>
1531
+ </p>
1532
+ <p>
1533
+ <%= f.label :body %><br />
1534
+ <%= f.text_area :body %>
1535
+ </p>
1536
+ <p>
1537
+ <%= f.submit %>
1538
+ </p>
1539
+ <% end %>
1540
+
1541
+ <%= link_to 'Edit Post', edit_post_path(@post) %> |
1542
+ <%= link_to 'Back to Posts', posts_path %>
1543
+ ```
1544
+
1545
+ This will now render the partial in `app/views/comments/_comment.html.erb` once
1546
+ for each comment that is in the `@post.comments` collection. As the `render`
1547
+ method iterates over the `@post.comments` collection, it assigns each
1548
+ comment to a local variable named the same as the partial, in this case
1549
+ `comment` which is then available in the partial for us to show.
1550
+
1551
+ ### Rendering a Partial Form
1552
+
1553
+ Let us also move that new comment section out to its own partial. Again, you
1554
+ create a file `app/views/comments/_form.html.erb` containing:
1555
+
1556
+ ```html+erb
1557
+ <%= form_for([@post, @post.comments.build]) do |f| %>
1558
+ <p>
1559
+ <%= f.label :commenter %><br />
1560
+ <%= f.text_field :commenter %>
1561
+ </p>
1562
+ <p>
1563
+ <%= f.label :body %><br />
1564
+ <%= f.text_area :body %>
1565
+ </p>
1566
+ <p>
1567
+ <%= f.submit %>
1568
+ </p>
1569
+ <% end %>
1570
+ ```
1571
+
1572
+ Then you make the `app/views/posts/show.html.erb` look like the following:
1573
+
1574
+ ```html+erb
1575
+ <p>
1576
+ <strong>Title:</strong>
1577
+ <%= @post.title %>
1578
+ </p>
1579
+
1580
+ <p>
1581
+ <strong>Text:</strong>
1582
+ <%= @post.text %>
1583
+ </p>
1584
+
1585
+ <h2>Comments</h2>
1586
+ <%= render @post.comments %>
1587
+
1588
+ <h2>Add a comment:</h2>
1589
+ <%= render "comments/form" %>
1590
+
1591
+ <%= link_to 'Edit Post', edit_post_path(@post) %> |
1592
+ <%= link_to 'Back to Posts', posts_path %>
1593
+ ```
1594
+
1595
+ The second render just defines the partial template we want to render,
1596
+ `comments/form`. Rails is smart enough to spot the forward slash in that
1597
+ string and realize that you want to render the `_form.html.erb` file in
1598
+ the `app/views/comments` directory.
1599
+
1600
+ The `@post` object is available to any partials rendered in the view because we
1601
+ defined it as an instance variable.
1602
+
1603
+ Deleting Comments
1604
+ -----------------
1605
+
1606
+ Another important feature of a blog is being able to delete spam comments. To do
1607
+ this, we need to implement a link of some sort in the view and a `DELETE` action
1608
+ in the `CommentsController`.
1609
+
1610
+ So first, let's add the delete link in the
1611
+ `app/views/comments/_comment.html.erb` partial:
1612
+
1613
+ ```html+erb
1614
+ <p>
1615
+ <strong>Commenter:</strong>
1616
+ <%= comment.commenter %>
1617
+ </p>
1618
+
1619
+ <p>
1620
+ <strong>Comment:</strong>
1621
+ <%= comment.body %>
1622
+ </p>
1623
+
1624
+ <p>
1625
+ <%= link_to 'Destroy Comment', [comment.post, comment],
1626
+ method: :delete,
1627
+ data: { confirm: 'Are you sure?' } %>
1628
+ </p>
1629
+ ```
1630
+
1631
+ Clicking this new "Destroy Comment" link will fire off a `DELETE
1632
+ /posts/:post_id/comments/:id` to our `CommentsController`, which can then use
1633
+ this to find the comment we want to delete, so let's add a destroy action to our
1634
+ controller (`app/controllers/comments_controller.rb`):
1635
+
1636
+ ```ruby
1637
+ class CommentsController < ApplicationController
1638
+
1639
+ def create
1640
+ @post = Post.find(params[:post_id])
1641
+ @comment = @post.comments.create(params[:comment])
1642
+ redirect_to post_path(@post)
1643
+ end
1644
+
1645
+ def destroy
1646
+ @post = Post.find(params[:post_id])
1647
+ @comment = @post.comments.find(params[:id])
1648
+ @comment.destroy
1649
+ redirect_to post_path(@post)
1650
+ end
1651
+
1652
+ end
1653
+ ```
1654
+
1655
+ The `destroy` action will find the post we are looking at, locate the comment
1656
+ within the `@post.comments` collection, and then remove it from the
1657
+ database and send us back to the show action for the post.
1658
+
1659
+
1660
+ ### Deleting Associated Objects
1661
+
1662
+ If you delete a post then its associated comments will also need to be deleted.
1663
+ Otherwise they would simply occupy space in the database. Rails allows you to
1664
+ use the `dependent` option of an association to achieve this. Modify the Post
1665
+ model, `app/models/post.rb`, as follows:
1666
+
1667
+ ```ruby
1668
+ class Post < ActiveRecord::Base
1669
+ has_many :comments, dependent: :destroy
1670
+ validates :title, presence: true,
1671
+ length: { minimum: 5 }
1672
+ [...]
1673
+ end
1674
+ ```
1675
+
1676
+ Security
1677
+ --------
1678
+
1679
+ If you were to publish your blog online, anybody would be able to add, edit and
1680
+ delete posts or delete comments.
1681
+
1682
+ Rails provides a very simple HTTP authentication system that will work nicely in
1683
+ this situation.
1684
+
1685
+ In the `PostsController` we need to have a way to block access to the various
1686
+ actions if the person is not authenticated, here we can use the Rails
1687
+ `http_basic_authenticate_with` method, allowing access to the requested
1688
+ action if that method allows it.
1689
+
1690
+ To use the authentication system, we specify it at the top of our
1691
+ `PostsController`, in this case, we want the user to be authenticated on every
1692
+ action, except for `index` and `show`, so we write that in `app/controllers/posts_controller.rb`:
1693
+
1694
+ ```ruby
1695
+ class PostsController < ApplicationController
1696
+
1697
+ http_basic_authenticate_with name: "dhh", password: "secret", except: [:index, :show]
1698
+
1699
+ def index
1700
+ @posts = Post.all
1701
+ end
1702
+
1703
+ # snipped for brevity
1704
+ ```
1705
+
1706
+ We also only want to allow authenticated users to delete comments, so in the
1707
+ `CommentsController` (`app/controllers/comments_controller.rb`) we write:
1708
+
1709
+ ```ruby
1710
+ class CommentsController < ApplicationController
1711
+
1712
+ http_basic_authenticate_with name: "dhh", password: "secret", only: :destroy
1713
+
1714
+ def create
1715
+ @post = Post.find(params[:post_id])
1716
+ ...
1717
+ end
1718
+ # snipped for brevity
1719
+ ```
1720
+
1721
+ Now if you try to create a new post, you will be greeted with a basic HTTP
1722
+ Authentication challenge
1723
+
1724
+ ![Basic HTTP Authentication Challenge](images/challenge.png)
1725
+
1726
+ What's Next?
1727
+ ------------
1728
+
1729
+ Now that you've seen your first Rails application, you should feel free to
1730
+ update it and experiment on your own. But you don't have to do everything
1731
+ without help. As you need assistance getting up and running with Rails, feel
1732
+ free to consult these support resources:
1733
+
1734
+ * The [Ruby on Rails guides](index.html)
1735
+ * The [Ruby on Rails Tutorial](http://railstutorial.org/book)
1736
+ * The [Ruby on Rails mailing list](http://groups.google.com/group/rubyonrails-talk)
1737
+ * The [#rubyonrails](irc://irc.freenode.net/#rubyonrails) channel on irc.freenode.net
1738
+
1739
+ Rails also comes with built-in help that you can generate using the rake command-line utility:
1740
+
1741
+ * Running `rake doc:guides` will put a full copy of the Rails Guides in the `doc/guides` folder of your application. Open `doc/guides/index.html` in your web browser to explore the Guides.
1742
+ * Running `rake doc:rails` will put a full copy of the API documentation for Rails in the `doc/api` folder of your application. Open `doc/api/index.html` in your web browser to explore the API documentation.
1743
+
1744
+ TIP: To be able to generate the Rails Guides locally with the `doc:guides` rake task you need to install the RedCloth gem. Add it to your `Gemfile` and run `bundle install` and you're ready to go.
1745
+
1746
+ Configuration Gotchas
1747
+ ---------------------
1748
+
1749
+ The easiest way to work with Rails is to store all external data as UTF-8. If
1750
+ you don't, Ruby libraries and Rails will often be able to convert your native
1751
+ data into UTF-8, but this doesn't always work reliably, so you're better off
1752
+ ensuring that all external data is UTF-8.
1753
+
1754
+ If you have made a mistake in this area, the most common symptom is a black
1755
+ diamond with a question mark inside appearing in the browser. Another common
1756
+ symptom is characters like "ü" appearing instead of "ü". Rails takes a number
1757
+ of internal steps to mitigate common causes of these problems that can be
1758
+ automatically detected and corrected. However, if you have external data that is
1759
+ not stored as UTF-8, it can occasionally result in these kinds of issues that
1760
+ cannot be automatically detected by Rails and corrected.
1761
+
1762
+ Two very common sources of data that are not UTF-8:
1763
+
1764
+ * Your text editor: Most text editors (such as Textmate), default to saving files as
1765
+ UTF-8. If your text editor does not, this can result in special characters that you
1766
+ enter in your templates (such as é) to appear as a diamond with a question mark inside
1767
+ in the browser. This also applies to your i18n translation files.
1768
+ Most editors that do not already default to UTF-8 (such as some versions of
1769
+ Dreamweaver) offer a way to change the default to UTF-8. Do so.
1770
+ * Your database. Rails defaults to converting data from your database into UTF-8 at
1771
+ the boundary. However, if your database is not using UTF-8 internally, it may not
1772
+ be able to store all characters that your users enter. For instance, if your database
1773
+ is using Latin-1 internally, and your user enters a Russian, Hebrew, or Japanese
1774
+ character, the data will be lost forever once it enters the database. If possible,
1775
+ use UTF-8 as the internal storage of your database.