rails_test 4.2.0.beta1

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