rails 4.1.14.2 → 5.2.4.4

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