rails 4.1.4 → 5.0.0

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