rails 4.1.0.beta2 → 4.1.0.rc1

Sign up to get free protection for your applications and to get access to all the features.
Files changed (59) hide show
  1. checksums.yaml +4 -4
  2. data/README.md +3 -3
  3. data/guides/assets/images/getting_started/article_with_comments.png +0 -0
  4. data/guides/assets/images/getting_started/challenge.png +0 -0
  5. data/guides/assets/images/getting_started/confirm_dialog.png +0 -0
  6. data/guides/assets/images/getting_started/forbidden_attributes_for_new_article.png +0 -0
  7. data/guides/assets/images/getting_started/form_with_errors.png +0 -0
  8. data/guides/assets/images/getting_started/index_action_with_edit_link.png +0 -0
  9. data/guides/assets/images/getting_started/new_article.png +0 -0
  10. data/guides/assets/images/getting_started/rails_welcome.jpg +0 -0
  11. data/guides/assets/images/getting_started/routing_error_no_controller.png +0 -0
  12. data/guides/assets/images/getting_started/{show_action_for_posts.png → show_action_for_articles.png} +0 -0
  13. data/guides/assets/images/getting_started/template_is_missing_articles_new.png +0 -0
  14. data/guides/assets/images/getting_started/unknown_action_create_for_articles.png +0 -0
  15. data/guides/assets/images/getting_started/unknown_action_new_for_articles.png +0 -0
  16. data/guides/bug_report_templates/action_controller_gem.rb +5 -2
  17. data/guides/bug_report_templates/active_record_gem.rb +4 -1
  18. data/guides/code/getting_started/Gemfile +20 -23
  19. data/guides/code/getting_started/Gemfile.lock +73 -67
  20. data/guides/code/getting_started/app/views/layouts/application.html.erb +2 -2
  21. data/guides/code/getting_started/config/environments/production.rb +2 -2
  22. data/guides/code/getting_started/config/environments/test.rb +1 -1
  23. data/guides/rails_guides/helpers.rb +2 -0
  24. data/guides/source/3_0_release_notes.md +1 -1
  25. data/guides/source/4_1_release_notes.md +181 -61
  26. data/guides/source/action_controller_overview.md +46 -7
  27. data/guides/source/action_mailer_basics.md +5 -5
  28. data/guides/source/active_record_querying.md +18 -18
  29. data/guides/source/active_record_validations.md +11 -9
  30. data/guides/source/active_support_core_extensions.md +13 -1
  31. data/guides/source/api_documentation_guidelines.md +52 -2
  32. data/guides/source/asset_pipeline.md +54 -22
  33. data/guides/source/association_basics.md +13 -0
  34. data/guides/source/configuring.md +159 -11
  35. data/guides/source/contributing_to_ruby_on_rails.md +7 -6
  36. data/guides/source/development_dependencies_install.md +2 -0
  37. data/guides/source/documents.yaml +1 -1
  38. data/guides/source/engines.md +4 -3
  39. data/guides/source/form_helpers.md +10 -3
  40. data/guides/source/getting_started.md +525 -478
  41. data/guides/source/i18n.md +4 -4
  42. data/guides/source/initialization.md +2 -2
  43. data/guides/source/layouts_and_rendering.md +38 -8
  44. data/guides/source/migrations.md +5 -5
  45. data/guides/source/plugins.md +0 -1
  46. data/guides/source/routing.md +4 -2
  47. data/guides/source/security.md +47 -4
  48. data/guides/source/testing.md +10 -31
  49. data/guides/source/upgrading_ruby_on_rails.md +121 -12
  50. data/guides/source/working_with_javascript_in_rails.md +1 -1
  51. metadata +23 -24
  52. data/guides/assets/images/getting_started/forbidden_attributes_for_new_post.png +0 -0
  53. data/guides/assets/images/getting_started/new_post.png +0 -0
  54. data/guides/assets/images/getting_started/post_with_comments.png +0 -0
  55. data/guides/assets/images/getting_started/rails_welcome.png +0 -0
  56. data/guides/assets/images/getting_started/template_is_missing_posts_new.png +0 -0
  57. data/guides/assets/images/getting_started/undefined_method_post_path.png +0 -0
  58. data/guides/assets/images/getting_started/unknown_action_create_for_posts.png +0 -0
  59. data/guides/assets/images/getting_started/unknown_action_new_for_posts.png +0 -0
@@ -490,6 +490,19 @@ end
490
490
 
491
491
  With this setup, you can retrieve `@employee.subordinates` and `@employee.manager`.
492
492
 
493
+ In your migrations/schema, you will add a references column to the model itself.
494
+
495
+ ```ruby
496
+ class CreateEmployees < ActiveRecord::Migration
497
+ def change
498
+ create_table :employees do |t|
499
+ t.references :manager
500
+ t.timestamps
501
+ end
502
+ end
503
+ end
504
+ ```
505
+
493
506
  Tips, Tricks, and Warnings
494
507
  --------------------------
495
508
 
@@ -137,7 +137,9 @@ numbers. New applications filter out passwords by adding the following `config.f
137
137
  * `config.assets.enabled` a flag that controls whether the asset
138
138
  pipeline is enabled. It is set to true by default.
139
139
 
140
- * `config.assets.compress` a flag that enables the compression of compiled assets. It is explicitly set to true in `config/production.rb`.
140
+ *`config.assets.raise_runtime_errors`* Set this flag to `true` to enable additional runtime error checking. Recommended in `config/environments/development.rb` to minimize unexpected behavior when deploying to `production`.
141
+
142
+ * `config.assets.compress` a flag that enables the compression of compiled assets. It is explicitly set to true in `config/environments/production.rb`.
141
143
 
142
144
  * `config.assets.css_compressor` defines the CSS compressor to use. It is set by default by `sass-rails`. The unique alternative value at the moment is `:yui`, which uses the `yui-compressor` gem.
143
145
 
@@ -244,8 +246,14 @@ config.middleware.delete "Rack::MethodOverride"
244
246
 
245
247
  ### Configuring i18n
246
248
 
249
+ All these configuration options are delegated to the `I18n` library.
250
+
251
+ * `config.i18n.available_locales` whitelists the available locales for the app. Defaults to all locale keys found in locale files, usually only `:en` on a new application.
252
+
247
253
  * `config.i18n.default_locale` sets the default locale of an application used for i18n. Defaults to `:en`.
248
254
 
255
+ * `config.i18n.enforce_available_locales` ensures that all locales passed through i18n must be declared in the `available_locales` list, raising an `I18n::InvalidLocale` exception when setting an unavailable locale. Defaults to `true`. It is recommended not to disable this option unless strongly required, since this works as a security measure against setting any invalid locale from user input.
256
+
249
257
  * `config.i18n.load_path` sets the path Rails uses to look for locale files. Defaults to `config/locales/*.{yml,rb}`.
250
258
 
251
259
  ### Configuring Active Record
@@ -282,6 +290,14 @@ config.middleware.delete "Rack::MethodOverride"
282
290
 
283
291
  * `config.active_record.attribute_types_cached_by_default` sets the attribute types that `ActiveRecord::AttributeMethods` will cache by default on reads. The default is `[:datetime, :timestamp, :time, :date]`.
284
292
 
293
+ * `config.active_record.maintain_test_schema` is a boolean value which controls whether Active Record should try to keep your test database schema up-to-date with `db/schema.rb` (or `db/structure.sql`) when you run your tests. The default is true.
294
+
295
+ * `config.active_record.dump_schema_after_migration` is a flag which
296
+ controls whether or not schema dump should happen (`db/schema.rb` or
297
+ `db/structure.sql`) when you run migrations. This is set to false in
298
+ `config/environments/production.rb` which is generated by Rails. The
299
+ default value is true if this configuration is not set.
300
+
285
301
  The MySQL adapter adds one additional configuration option:
286
302
 
287
303
  * `ActiveRecord::ConnectionAdapters::MysqlAdapter.emulate_booleans` controls whether Active Record will consider all `tinyint(1)` columns in a MySQL database to be booleans and is true by default.
@@ -342,6 +358,10 @@ value. Defaults to `'encrypted cookie'`.
342
358
  * `config.action_dispatch.encrypted_signed_cookie_salt` sets the signed
343
359
  encrypted cookies salt value. Defaults to `'signed encrypted cookie'`.
344
360
 
361
+ * `config.action_dispatch.perform_deep_munge` configures whether `deep_munge`
362
+ method should be performed on the parameters. See [Security Guide](security.html#unsafe-query-generation)
363
+ for more information. It defaults to true.
364
+
345
365
  * `ActionDispatch::Callbacks.before` takes a block of code to run before the request.
346
366
 
347
367
  * `ActionDispatch::Callbacks.to_prepare` takes a block to run after `ActionDispatch::Callbacks.before`, but before the request. Runs for every request in `development` mode, but only once for `production` or environments with `cache_classes` set to `true`.
@@ -364,7 +384,7 @@ encrypted cookies salt value. Defaults to `'signed encrypted cookie'`.
364
384
 
365
385
  * `config.action_view.logger` accepts a logger conforming to the interface of Log4r or the default Ruby Logger class, which is then used to log information from Action View. Set to `nil` to disable logging.
366
386
 
367
- * `config.action_view.erb_trim_mode` gives the trim mode to be used by ERB. It defaults to `'-'`. See the [ERB documentation](http://www.ruby-doc.org/stdlib/libdoc/erb/rdoc/) for more information.
387
+ * `config.action_view.erb_trim_mode` gives the trim mode to be used by ERB. It defaults to `'-'`, which turns on trimming of tail spaces and newline when using `<%= -%>` or `<%= =%>`. See the [Erubis documentation](http://www.kuwata-lab.com/erubis/users-guide.06.html#topics-trimspaces) for more information.
368
388
 
369
389
  * `config.action_view.embed_authenticity_token_in_remote_forms` allows you to set the default behavior for `authenticity_token` in forms with `:remote => true`. By default it's set to false, which means that remote forms will not include `authenticity_token`, which is helpful when you're fragment-caching the form. Remote forms get the authenticity from the `meta` tag, so embedding is unnecessary unless you support browsers without JavaScript. In such case you can either pass `:authenticity_token => true` as a form option or set this config setting to `true`
370
390
 
@@ -376,6 +396,8 @@ encrypted cookies salt value. Defaults to `'signed encrypted cookie'`.
376
396
 
377
397
  The default setting is `true`, which uses the partial at `/admin/posts/_post.erb`. Setting the value to `false` would render `/posts/_post.erb`, which is the same behavior as rendering from a non-namespaced controller such as `PostsController`.
378
398
 
399
+ * `config.action_view.raise_on_missing_translations` determines whether an error should be raised for missing translations
400
+
379
401
  ### Configuring Action Mailer
380
402
 
381
403
  There are a number of settings available on `config.action_mailer`:
@@ -396,17 +418,25 @@ There are a number of settings available on `config.action_mailer`:
396
418
 
397
419
  * `config.action_mailer.raise_delivery_errors` specifies whether to raise an error if email delivery cannot be completed. It defaults to true.
398
420
 
399
- * `config.action_mailer.delivery_method` defines the delivery method. The allowed values are `:smtp` (default), `:sendmail`, and `:test`.
421
+ * `config.action_mailer.delivery_method` defines the delivery method and defaults to `:smtp`. See the [configuration section in the Action Mailer guide](http://guides.rubyonrails.org/action_mailer_basics.html#action-mailer-configuration) for more info.
400
422
 
401
423
  * `config.action_mailer.perform_deliveries` specifies whether mail will actually be delivered and is true by default. It can be convenient to set it to false for testing.
402
424
 
403
425
  * `config.action_mailer.default_options` configures Action Mailer defaults. Use to set options like `from` or `reply_to` for every mailer. These default to:
404
426
 
405
427
  ```ruby
406
- :mime_version => "1.0",
407
- :charset => "UTF-8",
408
- :content_type => "text/plain",
409
- :parts_order => [ "text/plain", "text/enriched", "text/html" ]
428
+ mime_version: "1.0",
429
+ charset: "UTF-8",
430
+ content_type: "text/plain",
431
+ parts_order: ["text/plain", "text/enriched", "text/html"]
432
+ ```
433
+
434
+ Assign a hash to set additional options:
435
+
436
+ ```ruby
437
+ config.action_mailer.default_options = {
438
+ from: "noreply@example.com"
439
+ }
410
440
  ```
411
441
 
412
442
  * `config.action_mailer.observers` registers observers which will be notified when mail is delivered.
@@ -431,6 +461,8 @@ There are a few configuration options available in Active Support:
431
461
 
432
462
  * `config.active_support.use_standard_json_time_format` enables or disables serializing dates to ISO 8601 format. Defaults to `true`.
433
463
 
464
+ * `config.active_support.time_precision` sets the precision of JSON encoded time values. Defaults to `3`.
465
+
434
466
  * `ActiveSupport::Logger.silencer` is set to `false` to disable the ability to silence logging in a block. The default is `true`.
435
467
 
436
468
  * `ActiveSupport::Cache::Store.logger` specifies the logger to use within cache store operations.
@@ -441,18 +473,134 @@ There are a few configuration options available in Active Support:
441
473
 
442
474
  * `ActiveSupport::Deprecation.silenced` sets whether or not to display deprecation warnings.
443
475
 
444
- * `ActiveSupport::Logger.silencer` is set to `false` to disable the ability to silence logging in a block. The default is `true`.
445
476
 
446
477
  ### Configuring a Database
447
478
 
448
- Just about every Rails application will interact with a database. The database to use is specified in a configuration file called `config/database.yml`. If you open this file in a new Rails application, you'll see a default database configured to use SQLite3. The file contains sections for three different environments in which Rails can run by default:
479
+ Just about every Rails application will interact with a database. You can connect to the database by setting an environment variable `ENV['DATABASE_URL']` or by using a configuration file called `config/database.yml`.
480
+
481
+ Using the `config/database.yml` file you can specify all the information needed to access your database:
482
+
483
+ ```yaml
484
+ development:
485
+ adapter: postgresql
486
+ database: blog_development
487
+ pool: 5
488
+ ```
489
+
490
+ This will connect to the database named `blog_development` using the `postgresql` adapter. This same information can be stored in a URL and provided via an environment variable like this:
491
+
492
+ ```ruby
493
+ > puts ENV['DATABASE_URL']
494
+ postgresql://localhost/blog_development?pool=5
495
+ ```
496
+
497
+ The `config/database.yml` file contains sections for three different environments in which Rails can run by default:
449
498
 
450
499
  * The `development` environment is used on your development/local computer as you interact manually with the application.
451
500
  * The `test` environment is used when running automated tests.
452
501
  * The `production` environment is used when you deploy your application for the world to use.
453
502
 
503
+ If you wish, you can manually specify a URL inside of your `config/database.yml`
504
+
505
+ ```
506
+ development:
507
+ url: postgresql://localhost/blog_development?pool=5
508
+ ```
509
+
510
+ The `config/database.yml` file can contain ERB tags `<%= %>`. Anything in the tags will be evaluated as Ruby code. You can use this to pull out data from an environment variable or to perform calculations to generate the needed connection information.
511
+
512
+
454
513
  TIP: You don't have to update the database configurations manually. If you look at the options of the application generator, you will see that one of the options is named `--database`. This option allows you to choose an adapter from a list of the most used relational databases. You can even run the generator repeatedly: `cd .. && rails new blog --database=mysql`. When you confirm the overwriting of the `config/database.yml` file, your application will be configured for MySQL instead of SQLite. Detailed examples of the common database connections are below.
455
514
 
515
+
516
+ ### Connection Preference
517
+
518
+ Since there are two ways to set your connection, via environment variable it is important to understand how the two can interact.
519
+
520
+ If you have an empty `config/database.yml` file but your `ENV['DATABASE_URL']` is present, then Rails will connect to the database via your environment variable:
521
+
522
+ ```
523
+ $ cat config/database.yml
524
+
525
+ $ echo $DATABASE_URL
526
+ postgresql://localhost/my_database
527
+ ```
528
+
529
+ If you have a `config/database.yml` but no `ENV['DATABASE_URL']` then this file will be used to connect to your database:
530
+
531
+ ```
532
+ $ cat config/database.yml
533
+ development:
534
+ adapter: postgresql
535
+ database: my_database
536
+ host: localhost
537
+
538
+ $ echo $DATABASE_URL
539
+ ```
540
+
541
+ If you have both `config/database.yml` and `ENV['DATABASE_URL']` set then Rails will merge the configuration together. To better understand this we must see some examples.
542
+
543
+ When duplicate connection information is provided the environment variable will take precedence:
544
+
545
+ ```
546
+ $ cat config/database.yml
547
+ development:
548
+ adapter: sqlite3
549
+ database: NOT_my_database
550
+ host: localhost
551
+
552
+ $ echo $DATABASE_URL
553
+ postgresql://localhost/my_database
554
+
555
+ $ rails runner 'puts ActiveRecord::Base.connections'
556
+ {"development"=>{"adapter"=>"postgresql", "host"=>"localhost", "database"=>"my_database"}}
557
+ ```
558
+
559
+ Here the adapter, host, and database match the information in `ENV['DATABASE_URL']`.
560
+
561
+ If non-duplicate information is provided you will get all unique values, environment variable still takes precedence in cases of any conflicts.
562
+
563
+ ```
564
+ $ cat config/database.yml
565
+ development:
566
+ adapter: sqlite3
567
+ pool: 5
568
+
569
+ $ echo $DATABASE_URL
570
+ postgresql://localhost/my_database
571
+
572
+ $ rails runner 'puts ActiveRecord::Base.connections'
573
+ {"development"=>{"adapter"=>"postgresql", "host"=>"localhost", "database"=>"my_database", "pool"=>5}}
574
+ ```
575
+
576
+ Since pool is not in the `ENV['DATABASE_URL']` provided connection information its information is merged in. Since `adapter` is duplicate, the `ENV['DATABASE_URL']` connection information wins.
577
+
578
+ The only way to explicitly not use the connection information in `ENV['DATABASE_URL']` is to specify an explicit URL connection using the `"url"` sub key:
579
+
580
+ ```
581
+ $ cat config/database.yml
582
+ development:
583
+ url: sqlite3://localhost/NOT_my_database
584
+
585
+ $ echo $DATABASE_URL
586
+ postgresql://localhost/my_database
587
+
588
+ $ rails runner 'puts ActiveRecord::Base.connections'
589
+ {"development"=>{"adapter"=>"sqlite3", "host"=>"localhost", "database"=>"NOT_my_database"}}
590
+ ```
591
+
592
+ Here the connection information in `ENV['DATABASE_URL']` is ignored, note the different adapter and database name.
593
+
594
+ Since it is possible to embed ERB in your `config/database.yml` it is best practice to explicitly show you are using the `ENV['DATABASE_URL']` to connect to your database. This is especially useful in production since you should not commit secrets like your database password into your source control (such as Git).
595
+
596
+ ```
597
+ $ cat config/database.yml
598
+ production:
599
+ url: <%= ENV['DATABASE_URL'] %>
600
+ ```
601
+
602
+ Now the behavior is clear, that we are only using the connection information in `ENV['DATABASE_URL']`.
603
+
456
604
  #### Configuring an SQLite3 Database
457
605
 
458
606
  Rails comes with built-in support for [SQLite3](http://www.sqlite.org), which is a lightweight serverless database application. While a busy production environment may overload SQLite, it works well for development and testing. Rails defaults to using an SQLite database when creating a new project, but you can always change it later.
@@ -573,7 +721,7 @@ Rails will now prepend "/app1" when generating links.
573
721
 
574
722
  #### Using Passenger
575
723
 
576
- Passenger makes it easiy to run your application in a subdirectory. You can find
724
+ Passenger makes it easy to run your application in a subdirectory. You can find
577
725
  the relevant configuration in the
578
726
  [passenger manual](http://www.modrails.com/documentation/Users%20guide%20Apache.html#deploying_rails_to_sub_uri).
579
727
 
@@ -791,4 +939,4 @@ ActiveRecord::ConnectionTimeoutError - could not obtain a database connection wi
791
939
  If you get the above error, you might want to increase the size of connection
792
940
  pool by incrementing the `pool` option in `database.yml`
793
941
 
794
- NOTE. If you have enabled `Rails.threadsafe!` mode then there could be a chance that several threads may be accessing multiple connections simultaneously. So depending on your current request load, you could very well have multiple threads contending for a limited amount of connections.
942
+ NOTE. As Rails is multi-threaded by default, there could be a chance that several threads may be accessing multiple connections simultaneously. So depending on your current request load, you could very well have multiple threads contending for a limited amount of connections.
@@ -136,7 +136,7 @@ You can invoke `test_jdbcmysql`, `test_jdbcsqlite3` or `test_jdbcpostgresql` als
136
136
 
137
137
  The test suite runs with warnings enabled. Ideally, Ruby on Rails should issue no warnings, but there may be a few, as well as some from third-party libraries. Please ignore (or fix!) them, if any, and submit patches that do not issue new warnings.
138
138
 
139
- As of this writing (December, 2010) they are especially noisy with Ruby 1.9. If you are sure about what you are doing and would like to have a more clear output, there's a way to override the flag:
139
+ If you are sure about what you are doing and would like to have a more clear output, there's a way to override the flag:
140
140
 
141
141
  ```bash
142
142
  $ RUBYOPT=-W0 bundle exec rake test
@@ -201,7 +201,8 @@ If your comment simply says "+1", then odds are that other reviewers aren't goin
201
201
  Contributing to the Rails Documentation
202
202
  ---------------------------------------
203
203
 
204
- Ruby on Rails has two main sets of documentation: the guides help you in learning about Ruby on Rails, and the API is a reference.
204
+ Ruby on Rails has two main sets of documentation: the guides, which help you
205
+ learn about Ruby on Rails, and the API, which serves as a reference.
205
206
 
206
207
  You can help improve the Rails guides by making them more coherent, consistent or readable, adding missing information, correcting factual errors, fixing typos, or bringing it up to date with the latest edge Rails. To get involved in the translation of Rails guides, please see [Translating Rails Guides](https://wiki.github.com/rails/docrails/translating-rails-guides).
207
208
 
@@ -258,10 +259,10 @@ more if the source code is mounted in `/vagrant` as happens in the recommended
258
259
  workflow with the [rails-dev-box](https://github.com/rails/rails-dev-box).
259
260
 
260
261
  As a compromise, test what your code obviously affects, and if the change is
261
- not in railties run the whole test suite of the affected component. If all is
262
- green that's enough to propose your contribution. We have [Travis CI](https://travis-ci.org/rails/rails)
263
- as a safety net for catching unexpected breakages
264
- elsewhere.
262
+ not in railties, run the whole test suite of the affected component. If all
263
+ tests are passing, that's enough to propose your contribution. We have
264
+ [Travis CI](https://travis-ci.org/rails/rails) as a safety net for catching
265
+ unexpected breakages elsewhere.
265
266
 
266
267
  TIP: Changes that are cosmetic in nature and do not add anything substantial to the stability, functionality, or testability of Rails will generally not be accepted.
267
268
 
@@ -233,6 +233,8 @@ mysql> GRANT ALL PRIVILEGES ON activerecord_unittest.*
233
233
  to 'rails'@'localhost';
234
234
  mysql> GRANT ALL PRIVILEGES ON activerecord_unittest2.*
235
235
  to 'rails'@'localhost';
236
+ mysql> GRANT ALL PRIVILEGES ON inexistent_activerecord_unittest.*
237
+ to 'rails'@'localhost';
236
238
  ```
237
239
 
238
240
  and create the test databases:
@@ -117,7 +117,7 @@
117
117
  name: The Rails Initialization Process
118
118
  work_in_progress: true
119
119
  url: initialization.html
120
- description: This guide explains the internals of the Rails initialization process as of Rails 3.1
120
+ description: This guide explains the internals of the Rails initialization process as of Rails 4
121
121
  -
122
122
  name: Extending Rails
123
123
  documents:
@@ -959,8 +959,8 @@ self.author = Blorgh.author_class.find_or_create_by(name: author_name)
959
959
  Resulting in something a little shorter, and more implicit in its behavior. The
960
960
  `author_class` method should always return a `Class` object.
961
961
 
962
- Since we changed the `author_class` method to return a `String` instead of a
963
- `Class`, we must also modify our `belongs_to` definition in the `Blorgh::Post`
962
+ Since we changed the `author_class` method to return a `Class` instead of a
963
+ `String`, we must also modify our `belongs_to` definition in the `Blorgh::Post`
964
964
  model:
965
965
 
966
966
  ```ruby
@@ -1014,7 +1014,8 @@ application. The same thing goes if you want to use a standard initializer.
1014
1014
  For locales, simply place the locale files in the `config/locales` directory,
1015
1015
  just like you would in an application.
1016
1016
 
1017
- Testing an engine -----------------
1017
+ Testing an engine
1018
+ -----------------
1018
1019
 
1019
1020
  When an engine is generated, there is a smaller dummy application created inside
1020
1021
  it at `test/dummy`. This application is used as a mounting point for the engine,
@@ -751,7 +751,7 @@ You might want to render a form with a set of edit fields for each of a person's
751
751
  <%= form_for @person do |person_form| %>
752
752
  <%= person_form.text_field :name %>
753
753
  <% @person.addresses.each do |address| %>
754
- <%= person_form.fields_for address, index: address do |address_form|%>
754
+ <%= person_form.fields_for address, index: address.id do |address_form|%>
755
755
  <%= address_form.text_field :city %>
756
756
  <% end %>
757
757
  <% end %>
@@ -774,9 +774,16 @@ This will result in a `params` hash that looks like
774
774
  {'person' => {'name' => 'Bob', 'address' => {'23' => {'city' => 'Paris'}, '45' => {'city' => 'London'}}}}
775
775
  ```
776
776
 
777
- Rails knows that all these inputs should be part of the person hash because you called `fields_for` on the first form builder. By specifying an `:index` option you're telling Rails that instead of naming the inputs `person[address][city]` it should insert that index surrounded by [] between the address and the city. If you pass an Active Record object as we did then Rails will call `to_param` on it, which by default returns the database id. This is often useful as it is then easy to locate which Address record should be modified. You can pass numbers with some other significance, strings or even `nil` (which will result in an array parameter being created).
777
+ Rails knows that all these inputs should be part of the person hash because you
778
+ called `fields_for` on the first form builder. By specifying an `:index` option
779
+ you're telling Rails that instead of naming the inputs `person[address][city]`
780
+ it should insert that index surrounded by [] between the address and the city.
781
+ This is often useful as it is then easy to locate which Address record
782
+ should be modified. You can pass numbers with some other significance,
783
+ strings or even `nil` (which will result in an array parameter being created).
778
784
 
779
- To create more intricate nestings, you can specify the first part of the input name (`person[address]` in the previous example) explicitly, for example
785
+ To create more intricate nestings, you can specify the first part of the input
786
+ name (`person[address]` in the previous example) explicitly:
780
787
 
781
788
  ```erb
782
789
  <%= fields_for 'person[address][primary]', address, index: address do |address_form| %>
@@ -21,19 +21,22 @@ application from scratch. It does not assume that you have any prior experience
21
21
  with Rails. However, to get the most out of it, you need to have some
22
22
  prerequisites installed:
23
23
 
24
- * The [Ruby](http://www.ruby-lang.org/en/downloads) language version 1.9.3 or newer
25
- * The [RubyGems](http://rubygems.org) packaging system
26
- * To learn more about RubyGems, please read the [RubyGems Guides](http://guides.rubygems.org)
27
- * A working installation of the [SQLite3 Database](http://www.sqlite.org)
24
+ * The [Ruby](http://www.ruby-lang.org/en/downloads) language version 1.9.3 or newer.
25
+ * The [RubyGems](http://rubygems.org) packaging system, which is installed with Ruby
26
+ versions 1.9 and later. To learn more about RubyGems, please read the [RubyGems Guides](http://guides.rubygems.org).
27
+ * A working installation of the [SQLite3 Database](http://www.sqlite.org).
28
28
 
29
29
  Rails is a web application framework running on the Ruby programming language.
30
30
  If you have no prior experience with Ruby, you will find a very steep learning
31
- curve diving straight into Rails. There are some good free resources on the
32
- Internet for learning Ruby, including:
31
+ curve diving straight into Rails. There are several curated lists of online resources
32
+ for learning Ruby:
33
33
 
34
- * [Mr. Neighborly's Humble Little Ruby Book](http://www.humblelittlerubybook.com)
35
- * [Programming Ruby](http://www.ruby-doc.org/docs/ProgrammingRuby/)
36
- * [Why's (Poignant) Guide to Ruby](http://mislav.uniqpath.com/poignant-guide/)
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.
37
40
 
38
41
  What is Rails?
39
42
  --------------
@@ -54,11 +57,13 @@ learned elsewhere, you may have a less happy experience.
54
57
 
55
58
  The Rails philosophy includes two major guiding principles:
56
59
 
57
- * DRY - "Don't Repeat Yourself" - suggests that writing the same code over and
58
- over again is a bad thing.
59
- * Convention Over Configuration - means that Rails makes assumptions about what
60
- you want to do and how you're going to do it, rather than requiring you to
61
- specify every little thing through endless configuration files.
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.
62
67
 
63
68
  Creating a New Rails Project
64
69
  ----------------------------
@@ -73,9 +78,9 @@ By following along with this guide, you'll create a Rails project called
73
78
  (very) simple weblog. Before you can start building the application, you need to
74
79
  make sure that you have Rails itself installed.
75
80
 
76
- TIP: The examples below use `#` and `$` to denote superuser and regular
77
- user terminal prompts respectively in a UNIX-like OS. If you are using
78
- Windows, your prompt will look something like `c:\source_code>`
81
+ TIP: The examples below use `$` to represent your terminal prompt in a UNIX-like OS,
82
+ though it may have been customized to appear differently. If you are using Windows,
83
+ your prompt will look something like `c:\source_code>`
79
84
 
80
85
  ### Installing Rails
81
86
 
@@ -84,21 +89,35 @@ Open up a command line prompt. On Mac OS X open Terminal.app, on Windows choose
84
89
  dollar sign `$` should be run in the command line. Verify that you have a
85
90
  current version of Ruby installed:
86
91
 
92
+ TIP. A number of tools exist to help you quickly install Ruby and Ruby
93
+ on Rails on your system. Windows users can use [Rails Installer](http://railsinstaller.org),
94
+ while Mac OS X users can use [Rails One Click](http://railsoneclick.com).
95
+
87
96
  ```bash
88
97
  $ ruby -v
89
- ruby 2.0.0p247
98
+ ruby 2.0.0p353
90
99
  ```
91
100
 
101
+ If you don't have Ruby installed have a look at
102
+ [ruby-lang.org](https://www.ruby-lang.org/en/downloads/) for possible ways to
103
+ install Ruby on your platform.
104
+
105
+ Many popular UNIX-like OSes ship with an acceptable version of SQLite3. Windows
106
+ users and others can find installation instructions at [the SQLite3 website](http://www.sqlite.org).
107
+ Verify that it is correctly installed and in your PATH:
108
+
109
+ ```bash
110
+ $ sqlite3 --version
111
+ ```
112
+
113
+ The program should report its version.
114
+
92
115
  To install Rails, use the `gem install` command provided by RubyGems:
93
116
 
94
117
  ```bash
95
118
  $ gem install rails
96
119
  ```
97
120
 
98
- TIP. A number of tools exist to help you quickly install Ruby and Ruby
99
- on Rails on your system. Windows users can use [Rails Installer](http://railsinstaller.org),
100
- while Mac OS X users can use [Rails One Click](http://railsoneclick.com).
101
-
102
121
  To verify that you have everything installed correctly, you should be able to
103
122
  run the following:
104
123
 
@@ -106,7 +125,7 @@ run the following:
106
125
  $ rails --version
107
126
  ```
108
127
 
109
- If it says something like "Rails 4.0.0", you are ready to continue.
128
+ If it says something like "Rails 4.1.0", you are ready to continue.
110
129
 
111
130
  ### Creating the Blog Application
112
131
 
@@ -123,42 +142,40 @@ rights to create files, and type:
123
142
  $ rails new blog
124
143
  ```
125
144
 
126
- This will create a Rails application called Blog in a directory called blog and
145
+ This will create a Rails application called Blog in a `blog` directory and
127
146
  install the gem dependencies that are already mentioned in `Gemfile` using
128
147
  `bundle install`.
129
148
 
130
149
  TIP: You can see all of the command line options that the Rails application
131
150
  builder accepts by running `rails new -h`.
132
151
 
133
- After you create the blog application, switch to its folder to continue work
134
- directly in that application:
152
+ After you create the blog application, switch to its folder:
135
153
 
136
154
  ```bash
137
155
  $ cd blog
138
156
  ```
139
157
 
140
- The `rails new blog` command we ran above created a folder in your working
141
- directory called `blog`. The `blog` directory has a number of auto-generated
142
- files and folders that make up the structure of a Rails application. Most of the
143
- work in this tutorial will happen in the `app/` folder, but here's a basic
144
- rundown on the function of each of the files and folders that Rails created by default:
158
+ The `blog` directory has a number of auto-generated files and folders that make
159
+ up the structure of a Rails application. Most of the work in this tutorial will
160
+ happen in the `app` folder, but here's a basic rundown on the function of each
161
+ of the files and folders that Rails created by default:
145
162
 
146
163
  | File/Folder | Purpose |
147
164
  | ----------- | ------- |
148
165
  |app/|Contains the controllers, models, views, helpers, mailers and assets for your application. You'll focus on this folder for the remainder of this guide.|
149
166
  |bin/|Contains the rails script that starts your app and can contain other scripts you use to deploy or run your application.|
150
- |config/|Configure your application's runtime rules, routes, database, and more. This is covered in more detail in [Configuring Rails Applications](configuring.html)|
167
+ |config/|Configure your application's routes, database, and more. This is covered in more detail in [Configuring Rails Applications](configuring.html).|
151
168
  |config.ru|Rack configuration for Rack based servers used to start the application.|
152
169
  |db/|Contains your current database schema, as well as the database migrations.|
153
- |Gemfile<br>Gemfile.lock|These files allow you to specify what gem dependencies are needed for your Rails application. These files are used by the Bundler gem. For more information about Bundler, see [the Bundler website](http://gembundler.com) |
170
+ |Gemfile<br>Gemfile.lock|These files allow you to specify what gem dependencies are needed for your Rails application. These files are used by the Bundler gem. For more information about Bundler, see [the Bundler website](http://gembundler.com).|
154
171
  |lib/|Extended modules for your application.|
155
172
  |log/|Application log files.|
156
- |public/|The only folder seen to the world as-is. Contains the static files and compiled assets.|
173
+ |public/|The only folder seen by the world as-is. Contains static files and compiled assets.|
157
174
  |Rakefile|This file locates and loads tasks that can be run from the command line. The task definitions are defined throughout the components of Rails. Rather than changing Rakefile, you should add your own tasks by adding files to the lib/tasks directory of your application.|
158
175
  |README.rdoc|This is a brief instruction manual for your application. You should edit this file to tell others what your application does, how to set it up, and so on.|
159
- |test/|Unit tests, fixtures, and other test apparatus. These are covered in [Testing Rails Applications](testing.html)|
160
- |tmp/|Temporary files (like cache, pid and session files)|
161
- |vendor/|A place for all third-party code. In a typical Rails application, this includes Ruby Gems and the Rails source code (if you optionally install it into your project).|
176
+ |test/|Unit tests, fixtures, and other test apparatus. These are covered in [Testing Rails Applications](testing.html).|
177
+ |tmp/|Temporary files (like cache, pid, and session files).|
178
+ |vendor/|A place for all third-party code. In a typical Rails application this includes vendored gems.|
162
179
 
163
180
  Hello, Rails!
164
181
  -------------
@@ -170,7 +187,7 @@ get your Rails application server running.
170
187
 
171
188
  You actually have a functional Rails application already. To see it, you need to
172
189
  start a web server on your development machine. You can do this by running the
173
- following in the root directory of your rails application:
190
+ following in the `blog` directory:
174
191
 
175
192
  ```bash
176
193
  $ rails server
@@ -179,16 +196,17 @@ $ rails server
179
196
  TIP: Compiling CoffeeScript to JavaScript requires a JavaScript runtime and the
180
197
  absence of a runtime will give you an `execjs` error. Usually Mac OS X and
181
198
  Windows come with a JavaScript runtime installed. Rails adds the `therubyracer`
182
- gem to Gemfile in a commented line for new apps and you can uncomment if you
183
- need it. `therubyrhino` is the recommended runtime for JRuby users and is added
184
- by default to Gemfile in apps generated under JRuby. You can investigate about
185
- all the supported runtimes at [ExecJS](https://github.com/sstephenson/execjs#readme).
199
+ gem to the generated `Gemfile` in a commented line for new apps and you can
200
+ uncomment if you need it. `therubyrhino` is the recommended runtime for JRuby
201
+ users and is added by default to the `Gemfile` in apps generated under JRuby.
202
+ You can investigate about all the supported runtimes at
203
+ [ExecJS](https://github.com/sstephenson/execjs#readme).
186
204
 
187
- This will fire up WEBrick, a webserver built into Ruby by default. To see your
188
- application in action, open a browser window and navigate to <http://localhost:3000>.
189
- You should see the Rails default information page:
205
+ This will fire up WEBrick, a web server distributed with Ruby by default. To see
206
+ your application in action, open a browser window and navigate to
207
+ <http://localhost:3000>. You should see the Rails default information page:
190
208
 
191
- ![Welcome Aboard screenshot](images/getting_started/rails_welcome.png)
209
+ ![Welcome aboard screenshot](images/getting_started/rails_welcome.jpg)
192
210
 
193
211
  TIP: To stop the web server, hit Ctrl+C in the terminal window where it's
194
212
  running. To verify the server has stopped you should see your command prompt
@@ -197,7 +215,7 @@ dollar sign `$`. In development mode, Rails does not generally require you to
197
215
  restart the server; changes you make in files will be automatically picked up by
198
216
  the server.
199
217
 
200
- The "Welcome Aboard" page is the _smoke test_ for a new Rails application: it
218
+ The "Welcome aboard" page is the _smoke test_ for a new Rails application: it
201
219
  makes sure that you have your software configured correctly enough to serve a
202
220
  page. You can also click on the _About your application's environment_ link to
203
221
  see a summary of your application's environment.
@@ -216,8 +234,9 @@ it to a view.
216
234
  A view's purpose is to display this information in a human readable format. An
217
235
  important distinction to make is that it is the _controller_, not the view,
218
236
  where information is collected. The view should just display that information.
219
- By default, view templates are written in a language called ERB (Embedded Ruby)
220
- which is converted by the request cycle in Rails before being sent to the user.
237
+ By default, view templates are written in a language called eRuby (Embedded
238
+ Ruby) which is processed by the request cycle in Rails before being sent to the
239
+ user.
221
240
 
222
241
  To create a new controller, you will need to run the "controller" generator and
223
242
  tell it you want a controller called "welcome" with an action called "index",
@@ -231,7 +250,7 @@ Rails will create several files and a route for you.
231
250
 
232
251
  ```bash
233
252
  create app/controllers/welcome_controller.rb
234
- route get "welcome/index"
253
+ route get 'welcome/index'
235
254
  invoke erb
236
255
  create app/views/welcome
237
256
  create app/views/welcome/index.html.erb
@@ -262,23 +281,25 @@ of code:
262
281
  ### Setting the Application Home Page
263
282
 
264
283
  Now that we have made the controller and view, we need to tell Rails when we
265
- want `Hello, Rails!` to show up. In our case, we want it to show up when we
284
+ want "Hello, Rails!" to show up. In our case, we want it to show up when we
266
285
  navigate to the root URL of our site, <http://localhost:3000>. At the moment,
267
- "Welcome Aboard" is occupying that spot.
286
+ "Welcome aboard" is occupying that spot.
268
287
 
269
288
  Next, you have to tell Rails where your actual home page is located.
270
289
 
271
290
  Open the file `config/routes.rb` in your editor.
272
291
 
273
292
  ```ruby
274
- Blog::Application.routes.draw do
275
- get "welcome/index"
293
+ Rails.application.routes.draw do
294
+ get 'welcome/index'
276
295
 
277
296
  # The priority is based upon order of creation:
278
297
  # first created -> highest priority.
279
- # ...
298
+ #
280
299
  # You can have the root of your site routed with "root"
281
- # root "welcome#index"
300
+ # root 'welcome#index'
301
+ #
302
+ # ...
282
303
  ```
283
304
 
284
305
  This is your application's _routing file_ which holds entries in a special DSL
@@ -289,17 +310,18 @@ to a specific controller and action. Find the line beginning with `root` and
289
310
  uncomment it. It should look something like the following:
290
311
 
291
312
  ```ruby
292
- root "welcome#index"
313
+ root 'welcome#index'
293
314
  ```
294
315
 
295
- The `root "welcome#index"` tells Rails to map requests to the root of the
296
- application to the welcome controller's index action and `get "welcome/index"`
316
+ `root 'welcome#index'` tells Rails to map requests to the root of the
317
+ application to the welcome controller's index action and `get 'welcome/index'`
297
318
  tells Rails to map requests to <http://localhost:3000/welcome/index> to the
298
319
  welcome controller's index action. This was created earlier when you ran the
299
320
  controller generator (`rails generate controller welcome index`).
300
321
 
301
- If you navigate to <http://localhost:3000> in your browser, you'll see the
302
- `Hello, Rails!` message you put into `app/views/welcome/index.html.erb`,
322
+ Launch the web server again if you stopped it to generate the controller (`rails
323
+ server`) and navigate to <http://localhost:3000> in your browser. You'll see the
324
+ "Hello, Rails!" message you put into `app/views/welcome/index.html.erb`,
303
325
  indicating that this new route is indeed going to `WelcomeController`'s `index`
304
326
  action and is rendering the view correctly.
305
327
 
@@ -312,108 +334,112 @@ Now that you've seen how to create a controller, an action and a view, let's
312
334
  create something with a bit more substance.
313
335
 
314
336
  In the Blog application, you will now create a new _resource_. A resource is the
315
- term used for a collection of similar objects, such as posts, people or animals.
337
+ term used for a collection of similar objects, such as articles, people or
338
+ animals.
316
339
  You can create, read, update and destroy items for a resource and these
317
340
  operations are referred to as _CRUD_ operations.
318
341
 
319
342
  Rails provides a `resources` method which can be used to declare a standard REST
320
- resource. Here's what `config/routes.rb` should look like after the _post resource_
321
- is declared.
343
+ resource. Here's what `config/routes.rb` should look like after the
344
+ _article resource_ is declared.
322
345
 
323
346
  ```ruby
324
347
  Blog::Application.routes.draw do
325
348
 
326
- resources :posts
349
+ resources :articles
327
350
 
328
- root "welcome#index"
351
+ root 'welcome#index'
329
352
  end
330
353
  ```
331
354
 
332
355
  If you run `rake routes`, you'll see that it has defined routes for all the
333
356
  standard RESTful actions. The meaning of the prefix column (and other columns)
334
357
  will be seen later, but for now notice that Rails has inferred the
335
- singular form `post` and makes meaningful use of the distinction.
358
+ singular form `article` and makes meaningful use of the distinction.
336
359
 
337
360
  ```bash
338
361
  $ rake routes
339
- Prefix Verb URI Pattern Controller#Action
340
- posts GET /posts(.:format) posts#index
341
- POST /posts(.:format) posts#create
342
- new_post GET /posts/new(.:format) posts#new
343
- edit_post GET /posts/:id/edit(.:format) posts#edit
344
- post GET /posts/:id(.:format) posts#show
345
- PATCH /posts/:id(.:format) posts#update
346
- PUT /posts/:id(.:format) posts#update
347
- DELETE /posts/:id(.:format) posts#destroy
348
- root / welcome#index
349
- ```
350
-
351
- In the next section, you will add the ability to create new posts in your
362
+ Prefix Verb URI Pattern Controller#Action
363
+ articles GET /articles(.:format) articles#index
364
+ POST /articles(.:format) articles#create
365
+ new_article GET /articles/new(.:format) articles#new
366
+ edit_article GET /articles/:id/edit(.:format) articles#edit
367
+ article GET /articles/:id(.:format) articles#show
368
+ PATCH /articles/:id(.:format) articles#update
369
+ PUT /articles/:id(.:format) articles#update
370
+ DELETE /articles/:id(.:format) articles#destroy
371
+ root GET / welcome#index
372
+ ```
373
+
374
+ In the next section, you will add the ability to create new articles in your
352
375
  application and be able to view them. This is the "C" and the "R" from CRUD:
353
376
  creation and reading. The form for doing this will look like this:
354
377
 
355
- ![The new post form](images/getting_started/new_post.png)
378
+ ![The new article form](images/getting_started/new_article.png)
356
379
 
357
380
  It will look a little basic for now, but that's ok. We'll look at improving the
358
381
  styling for it afterwards.
359
382
 
360
383
  ### Laying down the ground work
361
384
 
362
- The first thing that you are going to need to create a new post within the
363
- application is a place to do that. A great place for that would be at `/posts/new`.
364
- With the route already defined, requests can now be made to `/posts/new` in the
365
- application. Navigate to <http://localhost:3000/posts/new> and you'll see a
366
- routing error:
385
+ Firstly, you need a place within the application to create a new article. A
386
+ great place for that would be at `/articles/new`. With the route already
387
+ defined, requests can now be made to `/articles/new` in the application.
388
+ Navigate to <http://localhost:3000/articles/new> and you'll see a routing
389
+ error:
367
390
 
368
- ![Another routing error, uninitialized constant PostsController](images/getting_started/routing_error_no_controller.png)
391
+ ![Another routing error, uninitialized constant ArticlesController](images/getting_started/routing_error_no_controller.png)
369
392
 
370
393
  This error occurs because the route needs to have a controller defined in order
371
394
  to serve the request. The solution to this particular problem is simple: create
372
- a controller called `PostsController`. You can do this by running this command:
395
+ a controller called `ArticlesController`. You can do this by running this
396
+ command:
373
397
 
374
398
  ```bash
375
- $ rails g controller posts
399
+ $ rails g controller articles
376
400
  ```
377
401
 
378
- If you open up the newly generated `app/controllers/posts_controller.rb` you'll
379
- see a fairly empty controller:
402
+ If you open up the newly generated `app/controllers/articles_controller.rb`
403
+ you'll see a fairly empty controller:
380
404
 
381
405
  ```ruby
382
- class PostsController < ApplicationController
406
+ class ArticlesController < ApplicationController
383
407
  end
384
408
  ```
385
409
 
386
- A controller is simply a class that is defined to inherit from `ApplicationController`.
410
+ A controller is simply a class that is defined to inherit from
411
+ `ApplicationController`.
387
412
  It's inside this class that you'll define methods that will become the actions
388
- for this controller. These actions will perform CRUD operations on the posts
413
+ for this controller. These actions will perform CRUD operations on the articles
389
414
  within our system.
390
415
 
391
- NOTE: There are `public`, `private` and `protected` methods in `Ruby`
392
- (for more details you can check on [Programming Ruby](http://www.ruby-doc.org/docs/ProgrammingRuby/)).
393
- But only `public` methods can be actions for controllers.
416
+ NOTE: There are `public`, `private` and `protected` methods in Ruby,
417
+ but only `public` methods can be actions for controllers.
418
+ For more details check out [Programming Ruby](http://www.ruby-doc.org/docs/ProgrammingRuby/).
394
419
 
395
- If you refresh <http://localhost:3000/posts/new> now, you'll get a new error:
420
+ If you refresh <http://localhost:3000/articles/new> now, you'll get a new error:
396
421
 
397
- ![Unknown action new for PostsController!](images/getting_started/unknown_action_new_for_posts.png)
422
+ ![Unknown action new for ArticlesController!](images/getting_started/unknown_action_new_for_articles.png)
398
423
 
399
- This error indicates that Rails cannot find the `new` action inside the `PostsController`
400
- that you just generated. This is because when controllers are generated in Rails
401
- they are empty by default, unless you tell it your wanted actions during the
402
- generation process.
424
+ This error indicates that Rails cannot find the `new` action inside the
425
+ `ArticlesController` that you just generated. This is because when controllers
426
+ are generated in Rails they are empty by default, unless you tell it
427
+ your wanted actions during the generation process.
403
428
 
404
429
  To manually define an action inside a controller, all you need to do is to
405
- define a new method inside the controller. Open `app/controllers/posts_controller.rb`
406
- and inside the `PostsController` class, define a `new` method like this:
430
+ define a new method inside the controller.
431
+ Open `app/controllers/articles_controller.rb` and inside the `ArticlesController`
432
+ class, define a `new` method like this:
407
433
 
408
434
  ```ruby
409
435
  def new
410
436
  end
411
437
  ```
412
438
 
413
- With the `new` method defined in `PostsController`, if you refresh <http://localhost:3000/posts/new>
414
- you'll see another error:
439
+ With the `new` method defined in `ArticlesController`, if you refresh
440
+ <http://localhost:3000/articles/new> you'll see another error:
415
441
 
416
- ![Template is missing for posts/new](images/getting_started/template_is_missing_posts_new.png)
442
+ ![Template is missing for articles/new](images/getting_started/template_is_missing_articles_new.png)
417
443
 
418
444
  You're getting this error now because Rails expects plain actions like this one
419
445
  to have views associated with them to display their information. With no view
@@ -423,16 +449,16 @@ In the above image, the bottom line has been truncated. Let's see what the full
423
449
  thing looks like:
424
450
 
425
451
  <blockquote>
426
- Missing template posts/new, application/new with {locale:[:en], formats:[:html], handlers:[:erb, :builder, :coffee]}. Searched in: * "/path/to/blog/app/views"
452
+ Missing template articles/new, application/new with {locale:[:en], formats:[:html], handlers:[:erb, :builder, :coffee]}. Searched in: * "/path/to/blog/app/views"
427
453
  </blockquote>
428
454
 
429
455
  That's quite a lot of text! Let's quickly go through and understand what each
430
456
  part of it does.
431
457
 
432
458
  The first part identifies what template is missing. In this case, it's the
433
- `posts/new` template. Rails will first look for this template. If not found,
459
+ `articles/new` template. Rails will first look for this template. If not found,
434
460
  then it will attempt to load a template called `application/new`. It looks for
435
- one here because the `PostsController` inherits from `ApplicationController`.
461
+ one here because the `ArticlesController` inherits from `ApplicationController`.
436
462
 
437
463
  The next part of the message contains a hash. The `:locale` key in this hash
438
464
  simply indicates what spoken language template should be retrieved. By default,
@@ -448,34 +474,35 @@ Templates within a basic Rails application like this are kept in a single
448
474
  location, but in more complex applications it could be many different paths.
449
475
 
450
476
  The simplest template that would work in this case would be one located at
451
- `app/views/posts/new.html.erb`. The extension of this file name is key: the
477
+ `app/views/articles/new.html.erb`. The extension of this file name is key: the
452
478
  first extension is the _format_ of the template, and the second extension is the
453
479
  _handler_ that will be used. Rails is attempting to find a template called
454
- `posts/new` within `app/views` for the application. The format for this template
455
- can only be `html` and the handler must be one of `erb`, `builder` or `coffee`.
456
- Because you want to create a new HTML form, you will be using the `ERB`
457
- language. Therefore the file should be called `posts/new.html.erb` and needs to
458
- be located inside the `app/views` directory of the application.
480
+ `articles/new` within `app/views` for the application. The format for this
481
+ template can only be `html` and the handler must be one of `erb`, `builder` or
482
+ `coffee`. Because you want to create a new HTML form, you will be using the `ERB`
483
+ language. Therefore the file should be called `articles/new.html.erb` and needs
484
+ to be located inside the `app/views` directory of the application.
459
485
 
460
- Go ahead now and create a new file at `app/views/posts/new.html.erb` and write
461
- this content in it:
486
+ Go ahead now and create a new file at `app/views/articles/new.html.erb` and
487
+ write this content in it:
462
488
 
463
489
  ```html
464
- <h1>New Post</h1>
490
+ <h1>New Article</h1>
465
491
  ```
466
492
 
467
- When you refresh <http://localhost:3000/posts/new> you'll now see that the page
468
- has a title. The route, controller, action and view are now working
469
- harmoniously! It's time to create the form for a new post.
493
+ When you refresh <http://localhost:3000/articles/new> you'll now see that the
494
+ page has a title. The route, controller, action and view are now working
495
+ harmoniously! It's time to create the form for a new article.
470
496
 
471
497
  ### The first form
472
498
 
473
499
  To create a form within this template, you will use a <em>form
474
500
  builder</em>. The primary form builder for Rails is provided by a helper
475
- method called `form_for`. To use this method, add this code into `app/views/posts/new.html.erb`:
501
+ method called `form_for`. To use this method, add this code into
502
+ `app/views/articles/new.html.erb`:
476
503
 
477
504
  ```html+erb
478
- <%= form_for :post do |f| %>
505
+ <%= form_for :article do |f| %>
479
506
  <p>
480
507
  <%= f.label :title %><br>
481
508
  <%= f.text_field :title %>
@@ -496,71 +523,72 @@ If you refresh the page now, you'll see the exact same form as in the example.
496
523
  Building forms in Rails is really just that easy!
497
524
 
498
525
  When you call `form_for`, you pass it an identifying object for this
499
- form. In this case, it's the symbol `:post`. This tells the `form_for`
526
+ form. In this case, it's the symbol `:article`. This tells the `form_for`
500
527
  helper what this form is for. Inside the block for this method, the
501
528
  `FormBuilder` object - represented by `f` - is used to build two labels and two
502
- text fields, one each for the title and text of a post. Finally, a call to
529
+ text fields, one each for the title and text of an article. Finally, a call to
503
530
  `submit` on the `f` object will create a submit button for the form.
504
531
 
505
532
  There's one problem with this form though. If you inspect the HTML that is
506
533
  generated, by viewing the source of the page, you will see that the `action`
507
- attribute for the form is pointing at `/posts/new`. This is a problem because
534
+ attribute for the form is pointing at `/articles/new`. This is a problem because
508
535
  this route goes to the very page that you're on right at the moment, and that
509
- route should only be used to display the form for a new post.
536
+ route should only be used to display the form for a new article.
510
537
 
511
538
  The form needs to use a different URL in order to go somewhere else.
512
539
  This can be done quite simply with the `:url` option of `form_for`.
513
540
  Typically in Rails, the action that is used for new form submissions
514
541
  like this is called "create", and so the form should be pointed to that action.
515
542
 
516
- Edit the `form_for` line inside `app/views/posts/new.html.erb` to look like this:
543
+ Edit the `form_for` line inside `app/views/articles/new.html.erb` to look like
544
+ this:
517
545
 
518
546
  ```html+erb
519
- <%= form_for :post, url: posts_path do |f| %>
547
+ <%= form_for :article, url: articles_path do |f| %>
520
548
  ```
521
549
 
522
- In this example, the `posts_path` helper is passed to the `:url` option.
550
+ In this example, the `articles_path` helper is passed to the `:url` option.
523
551
  To see what Rails will do with this, we look back at the output of
524
552
  `rake routes`:
525
553
 
526
554
  ```bash
527
555
  $ rake routes
528
- Prefix Verb URI Pattern Controller#Action
529
- posts GET /posts(.:format) posts#index
530
- POST /posts(.:format) posts#create
531
- new_post GET /posts/new(.:format) posts#new
532
- edit_post GET /posts/:id/edit(.:format) posts#edit
533
- post GET /posts/:id(.:format) posts#show
534
- PATCH /posts/:id(.:format) posts#update
535
- PUT /posts/:id(.:format) posts#update
536
- DELETE /posts/:id(.:format) posts#destroy
537
- root / welcome#index
538
- ```
539
-
540
- The `posts_path` helper tells Rails to point the form
541
- to the URI Pattern associated with the `posts` prefix; and
556
+ Prefix Verb URI Pattern Controller#Action
557
+ articles GET /articles(.:format) articles#index
558
+ POST /articles(.:format) articles#create
559
+ new_article GET /articles/new(.:format) articles#new
560
+ edit_article GET /articles/:id/edit(.:format) articles#edit
561
+ article GET /articles/:id(.:format) articles#show
562
+ PATCH /articles/:id(.:format) articles#update
563
+ PUT /articles/:id(.:format) articles#update
564
+ DELETE /articles/:id(.:format) articles#destroy
565
+ root GET / welcome#index
566
+ ```
567
+
568
+ The `articles_path` helper tells Rails to point the form
569
+ to the URI Pattern associated with the `articles` prefix; and
542
570
  the form will (by default) send a `POST` request
543
571
  to that route. This is associated with the
544
- `create` action of the current controller, the `PostsController`.
572
+ `create` action of the current controller, the `ArticlesController`.
545
573
 
546
574
  With the form and its associated route defined, you will be able to fill in the
547
575
  form and then click the submit button to begin the process of creating a new
548
- post, so go ahead and do that. When you submit the form, you should see a
576
+ article, so go ahead and do that. When you submit the form, you should see a
549
577
  familiar error:
550
578
 
551
- ![Unknown action create for PostsController](images/getting_started/unknown_action_create_for_posts.png)
579
+ ![Unknown action create for ArticlesController](images/getting_started/unknown_action_create_for_articles.png)
552
580
 
553
- You now need to create the `create` action within the `PostsController` for this
554
- to work.
581
+ You now need to create the `create` action within the `ArticlesController` for
582
+ this to work.
555
583
 
556
- ### Creating posts
584
+ ### Creating articles
557
585
 
558
586
  To make the "Unknown action" go away, you can define a `create` action within
559
- the `PostsController` class in `app/controllers/posts_controller.rb`, underneath
560
- the `new` action:
587
+ the `ArticlesController` class in `app/controllers/articles_controller.rb`,
588
+ underneath the `new` action:
561
589
 
562
590
  ```ruby
563
- class PostsController < ApplicationController
591
+ class ArticlesController < ApplicationController
564
592
  def new
565
593
  end
566
594
 
@@ -571,7 +599,7 @@ end
571
599
 
572
600
  If you re-submit the form now, you'll see another familiar error: a template is
573
601
  missing. That's ok, we can ignore that for now. What the `create` action should
574
- be doing is saving our new post to a database.
602
+ be doing is saving our new article to the database.
575
603
 
576
604
  When a form is submitted, the fields of the form are sent to Rails as
577
605
  _parameters_. These parameters can then be referenced inside the controller
@@ -580,12 +608,12 @@ look like, change the `create` action to this:
580
608
 
581
609
  ```ruby
582
610
  def create
583
- render text: params[:post].inspect
611
+ render plain: params[:article].inspect
584
612
  end
585
613
  ```
586
614
 
587
615
  The `render` method here is taking a very simple hash with a key of `text` and
588
- value of `params[:post].inspect`. The `params` method is the object which
616
+ value of `params[:article].inspect`. The `params` method is the object which
589
617
  represents the parameters (or fields) coming in from the form. The `params`
590
618
  method returns an `ActiveSupport::HashWithIndifferentAccess` object, which
591
619
  allows you to access the keys of the hash using either strings or symbols. In
@@ -595,14 +623,14 @@ If you re-submit the form one more time you'll now no longer get the missing
595
623
  template error. Instead, you'll see something that looks like the following:
596
624
 
597
625
  ```ruby
598
- {"title"=>"First post!", "text"=>"This is my first post."}
626
+ {"title"=>"First article!", "text"=>"This is my first article."}
599
627
  ```
600
628
 
601
- This action is now displaying the parameters for the post that are coming in
629
+ This action is now displaying the parameters for the article that are coming in
602
630
  from the form. However, this isn't really all that helpful. Yes, you can see the
603
631
  parameters but nothing in particular is being done with them.
604
632
 
605
- ### Creating the Post model
633
+ ### Creating the Article model
606
634
 
607
635
  Models in Rails use a singular name, and their corresponding database tables use
608
636
  a plural name. Rails provides a generator for creating models, which
@@ -610,17 +638,17 @@ most Rails developers tend to use when creating new models.
610
638
  To create the new model, run this command in your terminal:
611
639
 
612
640
  ```bash
613
- $ rails generate model Post title:string text:text
641
+ $ rails generate model Article title:string text:text
614
642
  ```
615
643
 
616
- With that command we told Rails that we want a `Post` model, together
644
+ With that command we told Rails that we want a `Article` model, together
617
645
  with a _title_ attribute of type string, and a _text_ attribute
618
- of type text. Those attributes are automatically added to the `posts`
619
- table in the database and mapped to the `Post` model.
646
+ of type text. Those attributes are automatically added to the `articles`
647
+ table in the database and mapped to the `Article` model.
620
648
 
621
649
  Rails responded by creating a bunch of files. For
622
- now, we're only interested in `app/models/post.rb` and
623
- `db/migrate/20120419084633_create_posts.rb` (your name could be a bit
650
+ now, we're only interested in `app/models/article.rb` and
651
+ `db/migrate/20140120191729_create_articles.rb` (your name could be a bit
624
652
  different). The latter is responsible
625
653
  for creating the database structure, which is what we'll look at next.
626
654
 
@@ -639,13 +667,13 @@ and it's possible to undo a migration after it's been applied to your database.
639
667
  Migration filenames include a timestamp to ensure that they're processed in the
640
668
  order that they were created.
641
669
 
642
- If you look in the `db/migrate/20120419084633_create_posts.rb` file (remember,
670
+ If you look in the `db/migrate/20140120191729_create_articles.rb` file (remember,
643
671
  yours will have a slightly different name), here's what you'll find:
644
672
 
645
673
  ```ruby
646
- class CreatePosts < ActiveRecord::Migration
674
+ class CreateArticles < ActiveRecord::Migration
647
675
  def change
648
- create_table :posts do |t|
676
+ create_table :articles do |t|
649
677
  t.string :title
650
678
  t.text :text
651
679
 
@@ -655,12 +683,12 @@ class CreatePosts < ActiveRecord::Migration
655
683
  end
656
684
  ```
657
685
 
658
- The above migration creates a method named `change` which will be called when you
659
- run this migration. The action defined in this method is also reversible, which
660
- means Rails knows how to reverse the change made by this migration, in case you
661
- want to reverse it later. When you run this migration it will create a
662
- `posts` table with one string column and a text column. It also creates two
663
- timestamp fields to allow Rails to track post creation and update times.
686
+ The above migration creates a method named `change` which will be called when
687
+ you run this migration. The action defined in this method is also reversible,
688
+ which means Rails knows how to reverse the change made by this migration,
689
+ in case you want to reverse it later. When you run this migration it will create
690
+ an `articles` table with one string column and a text column. It also creates
691
+ two timestamp fields to allow Rails to track article creation and update times.
664
692
 
665
693
  TIP: For more information about migrations, refer to [Rails Database
666
694
  Migrations](migrations.html).
@@ -671,14 +699,14 @@ At this point, you can use a rake command to run the migration:
671
699
  $ rake db:migrate
672
700
  ```
673
701
 
674
- Rails will execute this migration command and tell you it created the Posts
702
+ Rails will execute this migration command and tell you it created the Articles
675
703
  table.
676
704
 
677
705
  ```bash
678
- == CreatePosts: migrating ====================================================
679
- -- create_table(:posts)
706
+ == CreateArticles: migrating ==================================================
707
+ -- create_table(:articles)
680
708
  -> 0.0019s
681
- == CreatePosts: migrated (0.0020s) ===========================================
709
+ == CreateArticles: migrated (0.0020s) =========================================
682
710
  ```
683
711
 
684
712
  NOTE. Because you're working in the development environment by default, this
@@ -689,34 +717,35 @@ invoking the command: `rake db:migrate RAILS_ENV=production`.
689
717
 
690
718
  ### Saving data in the controller
691
719
 
692
- Back in `PostsController`, we need to change the `create` action
693
- to use the new `Post` model to save the data in the database. Open `app/controllers/posts_controller.rb`
694
- and change the `create` action to look like this:
720
+ Back in `ArticlesController`, we need to change the `create` action
721
+ to use the new `Article` model to save the data in the database.
722
+ Open `app/controllers/articles_controller.rb` and change the `create` action to
723
+ look like this:
695
724
 
696
725
  ```ruby
697
726
  def create
698
- @post = Post.new(params[:post])
727
+ @article = Article.new(params[:article])
699
728
 
700
- @post.save
701
- redirect_to @post
729
+ @article.save
730
+ redirect_to @article
702
731
  end
703
732
  ```
704
733
 
705
734
  Here's what's going on: every Rails model can be initialized with its
706
735
  respective attributes, which are automatically mapped to the respective
707
736
  database columns. In the first line we do just that
708
- (remember that `params[:post]` contains the attributes we're interested in).
709
- Then, `@post.save` is responsible for saving the model in the database.
737
+ (remember that `params[:article]` contains the attributes we're interested in).
738
+ Then, `@article.save` is responsible for saving the model in the database.
710
739
  Finally, we redirect the user to the `show` action, which we'll define later.
711
740
 
712
- TIP: As we'll see later, `@post.save` returns a boolean indicating
713
- whether the model was saved or not.
741
+ TIP: As we'll see later, `@article.save` returns a boolean indicating
742
+ whether the article was saved or not.
714
743
 
715
744
  If you now go to
716
- <http://localhost:3000/posts/new> you'll *almost* be able to create a post. Try
717
- it! You should get an error that looks like this:
745
+ <http://localhost:3000/articles/new> you'll *almost* be able to create an
746
+ article. Try it! You should get an error that looks like this:
718
747
 
719
- ![Forbidden attributes for new post](images/getting_started/forbidden_attributes_for_new_post.png)
748
+ ![Forbidden attributes for new article](images/getting_started/forbidden_attributes_for_new_article.png)
720
749
 
721
750
  Rails has several security features that help you write secure applications,
722
751
  and you're running into one of them now. This one is called
@@ -727,28 +756,28 @@ look like this:
727
756
 
728
757
  ```ruby
729
758
  def create
730
- @post = Post.new(post_params)
759
+ @article = Article.new(article_params)
731
760
 
732
- @post.save
733
- redirect_to @post
761
+ @article.save
762
+ redirect_to @article
734
763
  end
735
764
 
736
765
  private
737
- def post_params
738
- params.require(:post).permit(:title, :text)
766
+ def article_params
767
+ params.require(:article).permit(:title, :text)
739
768
  end
740
769
  ```
741
770
 
742
771
  See the `permit`? It allows us to accept both `title` and `text` in this
743
772
  action.
744
773
 
745
- TIP: Note that `def post_params` is private. This new approach prevents an
774
+ TIP: Note that `def article_params` is private. This new approach prevents an
746
775
  attacker from setting the model's attributes by manipulating the hash passed to
747
776
  the model.
748
777
  For more information, refer to
749
- [this blog post about Strong Parameters](http://weblog.rubyonrails.org/2012/3/21/strong-parameters/).
778
+ [this blog article about Strong Parameters](http://weblog.rubyonrails.org/2012/3/21/strong-parameters/).
750
779
 
751
- ### Showing Posts
780
+ ### Showing Articles
752
781
 
753
782
  If you submit the form again now, Rails will complain about not finding
754
783
  the `show` action. That's not very useful though, so let's add the
@@ -757,69 +786,71 @@ the `show` action. That's not very useful though, so let's add the
757
786
  As we have seen in the output of `rake routes`, the route for `show` action is
758
787
  as follows:
759
788
 
760
- ```ruby
761
- post GET /posts/:id(.:format) posts#show
789
+ ```
790
+ article GET /articles/:id(.:format) articles#show
762
791
  ```
763
792
 
764
793
  The special syntax `:id` tells rails that this route expects an `:id`
765
- parameter, which in our case will be the id of the post.
794
+ parameter, which in our case will be the id of the article.
766
795
 
767
796
  As we did before, we need to add the `show` action in
768
- `app/controllers/posts_controller.rb` and its respective view.
797
+ `app/controllers/articles_controller.rb` and its respective view.
769
798
 
770
799
  ```ruby
771
800
  def show
772
- @post = Post.find(params[:id])
801
+ @article = Article.find(params[:id])
773
802
  end
774
803
  ```
775
804
 
776
- A couple of things to note. We use `Post.find` to find the post we're
805
+ A couple of things to note. We use `Article.find` to find the article we're
777
806
  interested in, passing in `params[:id]` to get the `:id` parameter from the
778
807
  request. We also use an instance variable (prefixed by `@`) to hold a
779
- reference to the post object. We do this because Rails will pass all instance
808
+ reference to the article object. We do this because Rails will pass all instance
780
809
  variables to the view.
781
810
 
782
- Now, create a new file `app/views/posts/show.html.erb` with the following
811
+ Now, create a new file `app/views/articles/show.html.erb` with the following
783
812
  content:
784
813
 
785
814
  ```html+erb
786
815
  <p>
787
816
  <strong>Title:</strong>
788
- <%= @post.title %>
817
+ <%= @article.title %>
789
818
  </p>
790
819
 
791
820
  <p>
792
821
  <strong>Text:</strong>
793
- <%= @post.text %>
822
+ <%= @article.text %>
794
823
  </p>
795
824
  ```
796
825
 
797
- With this change, you should finally be able to create new posts.
798
- Visit <http://localhost:3000/posts/new> and give it a try!
826
+ With this change, you should finally be able to create new articles.
827
+ Visit <http://localhost:3000/articles/new> and give it a try!
799
828
 
800
- ![Show action for posts](images/getting_started/show_action_for_posts.png)
829
+ ![Show action for articles](images/getting_started/show_action_for_articles.png)
801
830
 
802
- ### Listing all posts
831
+ ### Listing all articles
803
832
 
804
- We still need a way to list all our posts, so let's do that.
833
+ We still need a way to list all our articles, so let's do that.
805
834
  The route for this as per output of `rake routes` is:
806
835
 
807
- ```ruby
808
- posts GET /posts(.:format) posts#index
836
+ ```
837
+ articles GET /articles(.:format) articles#index
809
838
  ```
810
839
 
811
- Add the corresponding `index` action for that route inside the `PostsController` in the `app/controllers/posts_controller.rb` file:
840
+ Add the corresponding `index` action for that route inside the
841
+ `ArticlesController` in the `app/controllers/articles_controller.rb` file:
812
842
 
813
843
  ```ruby
814
844
  def index
815
- @posts = Post.all
845
+ @articles = Article.all
816
846
  end
817
847
  ```
818
848
 
819
- And then finally a view for this action, located at `app/views/posts/index.html.erb`:
849
+ And then finally, add view for this action, located at
850
+ `app/views/articles/index.html.erb`:
820
851
 
821
852
  ```html+erb
822
- <h1>Listing posts</h1>
853
+ <h1>Listing articles</h1>
823
854
 
824
855
  <table>
825
856
  <tr>
@@ -827,70 +858,71 @@ And then finally a view for this action, located at `app/views/posts/index.html.
827
858
  <th>Text</th>
828
859
  </tr>
829
860
 
830
- <% @posts.each do |post| %>
861
+ <% @articles.each do |article| %>
831
862
  <tr>
832
- <td><%= post.title %></td>
833
- <td><%= post.text %></td>
863
+ <td><%= article.title %></td>
864
+ <td><%= article.text %></td>
834
865
  </tr>
835
866
  <% end %>
836
867
  </table>
837
868
  ```
838
869
 
839
- Now if you go to `http://localhost:3000/posts` you will see a list of all the
840
- posts that you have created.
870
+ Now if you go to `http://localhost:3000/articles` you will see a list of all the
871
+ articles that you have created.
841
872
 
842
873
  ### Adding links
843
874
 
844
- You can now create, show, and list posts. Now let's add some links to
875
+ You can now create, show, and list articles. Now let's add some links to
845
876
  navigate through pages.
846
877
 
847
878
  Open `app/views/welcome/index.html.erb` and modify it as follows:
848
879
 
849
880
  ```html+erb
850
881
  <h1>Hello, Rails!</h1>
851
- <%= link_to 'My Blog', controller: 'posts' %>
882
+ <%= link_to 'My Blog', controller: 'articles' %>
852
883
  ```
853
884
 
854
885
  The `link_to` method is one of Rails' built-in view helpers. It creates a
855
886
  hyperlink based on text to display and where to go - in this case, to the path
856
- for posts.
887
+ for articles.
857
888
 
858
- Let's add links to the other views as well, starting with adding this "New Post"
859
- link to `app/views/posts/index.html.erb`, placing it above the `<table>` tag:
889
+ Let's add links to the other views as well, starting with adding this
890
+ "New Article" link to `app/views/articles/index.html.erb`, placing it above the
891
+ `<table>` tag:
860
892
 
861
893
  ```erb
862
- <%= link_to 'New post', new_post_path %>
894
+ <%= link_to 'New article', new_article_path %>
863
895
  ```
864
896
 
865
- This link will allow you to bring up the form that lets you create a new post.
866
- You should also add a link to this template - `app/views/posts/new.html.erb` -
867
- to go back to the `index` action. Do this by adding this underneath the form in
868
- this template:
897
+ This link will allow you to bring up the form that lets you create a new article.
898
+
899
+ Also add a link in `app/views/articles/new.html.erb`, underneath the form, to
900
+ go back to the `index` action:
869
901
 
870
902
  ```erb
871
- <%= form_for :post do |f| %>
903
+ <%= form_for :article do |f| %>
872
904
  ...
873
905
  <% end %>
874
906
 
875
- <%= link_to 'Back', posts_path %>
907
+ <%= link_to 'Back', articles_path %>
876
908
  ```
877
909
 
878
- Finally, add another link to the `app/views/posts/show.html.erb` template to go
879
- back to the `index` action as well, so that people who are viewing a single post
880
- can go back and view the whole list again:
910
+ Finally, add another link to the `app/views/articles/show.html.erb` template to
911
+ go back to the `index` action as well, so that people who are viewing a single
912
+ article can go back and view the whole list again:
881
913
 
882
914
  ```html+erb
883
915
  <p>
884
916
  <strong>Title:</strong>
885
- <%= @post.title %>
917
+ <%= @article.title %>
886
918
  </p>
887
919
 
888
920
  <p>
889
921
  <strong>Text:</strong>
890
- <%= @post.text %>
922
+ <%= @article.text %>
891
923
  </p>
892
924
 
893
- <%= link_to 'Back', posts_path %>
925
+ <%= link_to 'Back', articles_path %>
894
926
  ```
895
927
 
896
928
  TIP: If you want to link to an action in the same controller, you don't
@@ -903,87 +935,88 @@ and restart the web server when a change is made.
903
935
 
904
936
  ### Adding Some Validation
905
937
 
906
- The model file, `app/models/post.rb` is about as simple as it can get:
938
+ The model file, `app/models/article.rb` is about as simple as it can get:
907
939
 
908
940
  ```ruby
909
- class Post < ActiveRecord::Base
941
+ class Article < ActiveRecord::Base
910
942
  end
911
943
  ```
912
944
 
913
- There isn't much to this file - but note that the `Post` class inherits from
945
+ There isn't much to this file - but note that the `Article` class inherits from
914
946
  `ActiveRecord::Base`. Active Record supplies a great deal of functionality to
915
947
  your Rails models for free, including basic database CRUD (Create, Read, Update,
916
948
  Destroy) operations, data validation, as well as sophisticated search support
917
949
  and the ability to relate multiple models to one another.
918
950
 
919
951
  Rails includes methods to help you validate the data that you send to models.
920
- Open the `app/models/post.rb` file and edit it:
952
+ Open the `app/models/article.rb` file and edit it:
921
953
 
922
954
  ```ruby
923
- class Post < ActiveRecord::Base
955
+ class Article < ActiveRecord::Base
924
956
  validates :title, presence: true,
925
957
  length: { minimum: 5 }
926
958
  end
927
959
  ```
928
960
 
929
- These changes will ensure that all posts have a title that is at least five
961
+ These changes will ensure that all articles have a title that is at least five
930
962
  characters long. Rails can validate a variety of conditions in a model,
931
963
  including the presence or uniqueness of columns, their format, and the
932
964
  existence of associated objects. Validations are covered in detail in [Active
933
965
  Record Validations](active_record_validations.html)
934
966
 
935
- With the validation now in place, when you call `@post.save` on an invalid
936
- post, it will return `false`. If you open `app/controllers/posts_controller.rb`
937
- again, you'll notice that we don't check the result of calling `@post.save`
938
- inside the `create` action. If `@post.save` fails in this situation, we need to
939
- show the form back to the user. To do this, change the `new` and `create`
940
- actions inside `app/controllers/posts_controller.rb` to these:
967
+ With the validation now in place, when you call `@article.save` on an invalid
968
+ article, it will return `false`. If you open
969
+ `app/controllers/articles_controller.rb` again, you'll notice that we don't
970
+ check the result of calling `@article.save` inside the `create` action.
971
+ If `@article.save` fails in this situation, we need to show the form back to the
972
+ user. To do this, change the `new` and `create` actions inside
973
+ `app/controllers/articles_controller.rb` to these:
941
974
 
942
975
  ```ruby
943
976
  def new
944
- @post = Post.new
977
+ @article = Article.new
945
978
  end
946
979
 
947
980
  def create
948
- @post = Post.new(post_params)
981
+ @article = Article.new(article_params)
949
982
 
950
- if @post.save
951
- redirect_to @post
983
+ if @article.save
984
+ redirect_to @article
952
985
  else
953
986
  render 'new'
954
987
  end
955
988
  end
956
989
 
957
990
  private
958
- def post_params
959
- params.require(:post).permit(:title, :text)
991
+ def article_params
992
+ params.require(:article).permit(:title, :text)
960
993
  end
961
994
  ```
962
995
 
963
- The `new` action is now creating a new instance variable called `@post`, and
996
+ The `new` action is now creating a new instance variable called `@article`, and
964
997
  you'll see why that is in just a few moments.
965
998
 
966
999
  Notice that inside the `create` action we use `render` instead of `redirect_to`
967
- when `save` returns `false`. The `render` method is used so that the `@post`
1000
+ when `save` returns `false`. The `render` method is used so that the `@article`
968
1001
  object is passed back to the `new` template when it is rendered. This rendering
969
- is done within the same request as the form submission, whereas the `redirect_to`
970
- will tell the browser to issue another request.
1002
+ is done within the same request as the form submission, whereas the
1003
+ `redirect_to` will tell the browser to issue another request.
971
1004
 
972
1005
  If you reload
973
- <http://localhost:3000/posts/new> and
974
- try to save a post without a title, Rails will send you back to the
1006
+ <http://localhost:3000/articles/new> and
1007
+ try to save an article without a title, Rails will send you back to the
975
1008
  form, but that's not very useful. You need to tell the user that
976
1009
  something went wrong. To do that, you'll modify
977
- `app/views/posts/new.html.erb` to check for error messages:
1010
+ `app/views/articles/new.html.erb` to check for error messages:
978
1011
 
979
1012
  ```html+erb
980
- <%= form_for :post, url: posts_path do |f| %>
981
- <% if @post.errors.any? %>
1013
+ <%= form_for :article, url: articles_path do |f| %>
1014
+ <% if @article.errors.any? %>
982
1015
  <div id="error_explanation">
983
- <h2><%= pluralize(@post.errors.count, "error") %> prohibited
984
- this post from being saved:</h2>
1016
+ <h2><%= pluralize(@article.errors.count, "error") %> prohibited
1017
+ this article from being saved:</h2>
985
1018
  <ul>
986
- <% @post.errors.full_messages.each do |msg| %>
1019
+ <% @article.errors.full_messages.each do |msg| %>
987
1020
  <li><%= msg %></li>
988
1021
  <% end %>
989
1022
  </ul>
@@ -1004,57 +1037,58 @@ something went wrong. To do that, you'll modify
1004
1037
  </p>
1005
1038
  <% end %>
1006
1039
 
1007
- <%= link_to 'Back', posts_path %>
1040
+ <%= link_to 'Back', articles_path %>
1008
1041
  ```
1009
1042
 
1010
1043
  A few things are going on. We check if there are any errors with
1011
- `@post.errors.any?`, and in that case we show a list of all
1012
- errors with `@post.errors.full_messages`.
1044
+ `@article.errors.any?`, and in that case we show a list of all
1045
+ errors with `@article.errors.full_messages`.
1013
1046
 
1014
1047
  `pluralize` is a rails helper that takes a number and a string as its
1015
1048
  arguments. If the number is greater than one, the string will be automatically
1016
1049
  pluralized.
1017
1050
 
1018
- The reason why we added `@post = Post.new` in the `PostsController` is that
1019
- otherwise `@post` would be `nil` in our view, and calling
1020
- `@post.errors.any?` would throw an error.
1051
+ The reason why we added `@article = Article.new` in the `ArticlesController` is
1052
+ that otherwise `@article` would be `nil` in our view, and calling
1053
+ `@article.errors.any?` would throw an error.
1021
1054
 
1022
1055
  TIP: Rails automatically wraps fields that contain an error with a div
1023
1056
  with class `field_with_errors`. You can define a css rule to make them
1024
1057
  standout.
1025
1058
 
1026
- Now you'll get a nice error message when saving a post without title when you
1027
- attempt to do just that on the new post form [(http://localhost:3000/posts/new)](http://localhost:3000/posts/new).
1059
+ Now you'll get a nice error message when saving an article without title when
1060
+ you attempt to do just that on the new article form
1061
+ [(http://localhost:3000/articles/new)](http://localhost:3000/articles/new).
1028
1062
 
1029
1063
  ![Form With Errors](images/getting_started/form_with_errors.png)
1030
1064
 
1031
- ### Updating Posts
1065
+ ### Updating Articles
1032
1066
 
1033
1067
  We've covered the "CR" part of CRUD. Now let's focus on the "U" part, updating
1034
- posts.
1068
+ articles.
1035
1069
 
1036
- The first step we'll take is adding an `edit` action to the `PostsController`.
1070
+ The first step we'll take is adding an `edit` action to the `ArticlesController`.
1037
1071
 
1038
1072
  ```ruby
1039
1073
  def edit
1040
- @post = Post.find(params[:id])
1074
+ @article = Article.find(params[:id])
1041
1075
  end
1042
1076
  ```
1043
1077
 
1044
1078
  The view will contain a form similar to the one we used when creating
1045
- new posts. Create a file called `app/views/posts/edit.html.erb` and make
1079
+ new articles. Create a file called `app/views/articles/edit.html.erb` and make
1046
1080
  it look as follows:
1047
1081
 
1048
1082
  ```html+erb
1049
- <h1>Editing post</h1>
1083
+ <h1>Editing article</h1>
1050
1084
 
1051
- <%= form_for :post, url: post_path(@post), method: :patch do |f| %>
1052
- <% if @post.errors.any? %>
1085
+ <%= form_for :article, url: article_path(@article), method: :patch do |f| %>
1086
+ <% if @article.errors.any? %>
1053
1087
  <div id="error_explanation">
1054
- <h2><%= pluralize(@post.errors.count, "error") %> prohibited
1055
- this post from being saved:</h2>
1088
+ <h2><%= pluralize(@article.errors.count, "error") %> prohibited
1089
+ this article from being saved:</h2>
1056
1090
  <ul>
1057
- <% @post.errors.full_messages.each do |msg| %>
1091
+ <% @article.errors.full_messages.each do |msg| %>
1058
1092
  <li><%= msg %></li>
1059
1093
  <% end %>
1060
1094
  </ul>
@@ -1075,7 +1109,7 @@ it look as follows:
1075
1109
  </p>
1076
1110
  <% end %>
1077
1111
 
1078
- <%= link_to 'Back', posts_path %>
1112
+ <%= link_to 'Back', articles_path %>
1079
1113
  ```
1080
1114
 
1081
1115
  This time we point the form to the `update` action, which is not defined yet
@@ -1085,42 +1119,48 @@ The `method: :patch` option tells Rails that we want this form to be submitted
1085
1119
  via the `PATCH` HTTP method which is the HTTP method you're expected to use to
1086
1120
  **update** resources according to the REST protocol.
1087
1121
 
1088
- TIP: By default forms built with the _form_for_ helper are sent via `POST`.
1122
+ The first parameter of the `form_tag` can be an object, say, `@article` which would
1123
+ cause the helper to fill in the form with the fields of the object. Passing in a
1124
+ symbol (`:article`) with the same name as the instance variable (`@article`) also
1125
+ automagically leads to the same behavior. This is what is happening here. More details
1126
+ can be found in [form_for documentation](http://api.rubyonrails.org/classes/ActionView/Helpers/FormHelper.html#method-i-form_for).
1089
1127
 
1090
- Next we need to create the `update` action in `app/controllers/posts_controller.rb`:
1128
+ Next we need to create the `update` action in
1129
+ `app/controllers/articles_controller.rb`:
1091
1130
 
1092
1131
  ```ruby
1093
1132
  def update
1094
- @post = Post.find(params[:id])
1133
+ @article = Article.find(params[:id])
1095
1134
 
1096
- if @post.update(post_params)
1097
- redirect_to @post
1135
+ if @article.update(article_params)
1136
+ redirect_to @article
1098
1137
  else
1099
1138
  render 'edit'
1100
1139
  end
1101
1140
  end
1102
1141
 
1103
1142
  private
1104
- def post_params
1105
- params.require(:post).permit(:title, :text)
1143
+ def article_params
1144
+ params.require(:article).permit(:title, :text)
1106
1145
  end
1107
1146
  ```
1108
1147
 
1109
1148
  The new method, `update`, is used when you want to update a record
1110
1149
  that already exists, and it accepts a hash containing the attributes
1111
1150
  that you want to update. As before, if there was an error updating the
1112
- post we want to show the form back to the user.
1151
+ article we want to show the form back to the user.
1113
1152
 
1114
- We reuse the `post_params` method that we defined earlier for the create action.
1153
+ We reuse the `article_params` method that we defined earlier for the create
1154
+ action.
1115
1155
 
1116
1156
  TIP: You don't need to pass all attributes to `update`. For
1117
- example, if you'd call `@post.update(title: 'A new title')`
1157
+ example, if you'd call `@article.update(title: 'A new title')`
1118
1158
  Rails would only update the `title` attribute, leaving all other
1119
1159
  attributes untouched.
1120
1160
 
1121
1161
  Finally, we want to show a link to the `edit` action in the list of all the
1122
- posts, so let's add that now to `app/views/posts/index.html.erb` to make it
1123
- appear next to the "Show" link:
1162
+ articles, so let's add that now to `app/views/articles/index.html.erb` to make
1163
+ it appear next to the "Show" link:
1124
1164
 
1125
1165
  ```html+erb
1126
1166
  <table>
@@ -1130,26 +1170,26 @@ appear next to the "Show" link:
1130
1170
  <th colspan="2"></th>
1131
1171
  </tr>
1132
1172
 
1133
- <% @posts.each do |post| %>
1173
+ <% @articles.each do |article| %>
1134
1174
  <tr>
1135
- <td><%= post.title %></td>
1136
- <td><%= post.text %></td>
1137
- <td><%= link_to 'Show', post_path(post) %></td>
1138
- <td><%= link_to 'Edit', edit_post_path(post) %></td>
1175
+ <td><%= article.title %></td>
1176
+ <td><%= article.text %></td>
1177
+ <td><%= link_to 'Show', article_path(article) %></td>
1178
+ <td><%= link_to 'Edit', edit_article_path(article) %></td>
1139
1179
  </tr>
1140
1180
  <% end %>
1141
1181
  </table>
1142
1182
  ```
1143
1183
 
1144
- And we'll also add one to the `app/views/posts/show.html.erb` template as well,
1145
- so that there's also an "Edit" link on a post's page. Add this at the bottom of
1146
- the template:
1184
+ And we'll also add one to the `app/views/articles/show.html.erb` template as
1185
+ well, so that there's also an "Edit" link on an article's page. Add this at the
1186
+ bottom of the template:
1147
1187
 
1148
1188
  ```html+erb
1149
1189
  ...
1150
1190
 
1151
- <%= link_to 'Back', posts_path %>
1152
- | <%= link_to 'Edit', edit_post_path(@post) %>
1191
+ <%= link_to 'Back', articles_path %>
1192
+ | <%= link_to 'Edit', edit_article_path(@article) %>
1153
1193
  ```
1154
1194
 
1155
1195
  And here's how our app looks so far:
@@ -1166,17 +1206,17 @@ underscore.
1166
1206
  TIP: You can read more about partials in the
1167
1207
  [Layouts and Rendering in Rails](layouts_and_rendering.html) guide.
1168
1208
 
1169
- Create a new file `app/views/posts/_form.html.erb` with the following
1209
+ Create a new file `app/views/articles/_form.html.erb` with the following
1170
1210
  content:
1171
1211
 
1172
1212
  ```html+erb
1173
- <%= form_for @post do |f| %>
1174
- <% if @post.errors.any? %>
1213
+ <%= form_for @article do |f| %>
1214
+ <% if @article.errors.any? %>
1175
1215
  <div id="error_explanation">
1176
- <h2><%= pluralize(@post.errors.count, "error") %> prohibited
1177
- this post from being saved:</h2>
1216
+ <h2><%= pluralize(@article.errors.count, "error") %> prohibited
1217
+ this article from being saved:</h2>
1178
1218
  <ul>
1179
- <% @post.errors.full_messages.each do |msg| %>
1219
+ <% @article.errors.full_messages.each do |msg| %>
1180
1220
  <li><%= msg %></li>
1181
1221
  <% end %>
1182
1222
  </ul>
@@ -1200,41 +1240,41 @@ content:
1200
1240
 
1201
1241
  Everything except for the `form_for` declaration remained the same.
1202
1242
  The reason we can use this shorter, simpler `form_for` declaration
1203
- to stand in for either of the other forms is that `@post` is a *resource*
1243
+ to stand in for either of the other forms is that `@article` is a *resource*
1204
1244
  corresponding to a full set of RESTful routes, and Rails is able to infer
1205
1245
  which URI and method to use.
1206
1246
  For more information about this use of `form_for`, see
1207
1247
  [Resource-oriented style](//api.rubyonrails.org/classes/ActionView/Helpers/FormHelper.html#method-i-form_for-label-Resource-oriented+style).
1208
1248
 
1209
- Now, let's update the `app/views/posts/new.html.erb` view to use this new
1249
+ Now, let's update the `app/views/articles/new.html.erb` view to use this new
1210
1250
  partial, rewriting it completely:
1211
1251
 
1212
1252
  ```html+erb
1213
- <h1>New post</h1>
1253
+ <h1>New article</h1>
1214
1254
 
1215
1255
  <%= render 'form' %>
1216
1256
 
1217
- <%= link_to 'Back', posts_path %>
1257
+ <%= link_to 'Back', articles_path %>
1218
1258
  ```
1219
1259
 
1220
- Then do the same for the `app/views/posts/edit.html.erb` view:
1260
+ Then do the same for the `app/views/articles/edit.html.erb` view:
1221
1261
 
1222
1262
  ```html+erb
1223
- <h1>Edit post</h1>
1263
+ <h1>Edit article</h1>
1224
1264
 
1225
1265
  <%= render 'form' %>
1226
1266
 
1227
- <%= link_to 'Back', posts_path %>
1267
+ <%= link_to 'Back', articles_path %>
1228
1268
  ```
1229
1269
 
1230
- ### Deleting Posts
1270
+ ### Deleting Articles
1231
1271
 
1232
- We're now ready to cover the "D" part of CRUD, deleting posts from the
1272
+ We're now ready to cover the "D" part of CRUD, deleting articles from the
1233
1273
  database. Following the REST convention, the route for
1234
- deleting posts as per output of `rake routes` is:
1274
+ deleting articles as per output of `rake routes` is:
1235
1275
 
1236
1276
  ```ruby
1237
- DELETE /posts/:id(.:format) posts#destroy
1277
+ DELETE /articles/:id(.:format) articles#destroy
1238
1278
  ```
1239
1279
 
1240
1280
  The `delete` routing method should be used for routes that destroy
@@ -1242,19 +1282,19 @@ resources. If this was left as a typical `get` route, it could be possible for
1242
1282
  people to craft malicious URLs like this:
1243
1283
 
1244
1284
  ```html
1245
- <a href='http://example.com/posts/1/destroy'>look at this cat!</a>
1285
+ <a href='http://example.com/articles/1/destroy'>look at this cat!</a>
1246
1286
  ```
1247
1287
 
1248
1288
  We use the `delete` method for destroying resources, and this route is mapped to
1249
- the `destroy` action inside `app/controllers/posts_controller.rb`, which doesn't
1250
- exist yet, but is provided below:
1289
+ the `destroy` action inside `app/controllers/articles_controller.rb`, which
1290
+ doesn't exist yet, but is provided below:
1251
1291
 
1252
1292
  ```ruby
1253
1293
  def destroy
1254
- @post = Post.find(params[:id])
1255
- @post.destroy
1294
+ @article = Article.find(params[:id])
1295
+ @article.destroy
1256
1296
 
1257
- redirect_to posts_path
1297
+ redirect_to articles_path
1258
1298
  end
1259
1299
  ```
1260
1300
 
@@ -1263,12 +1303,12 @@ them from the database. Note that we don't need to add a view for this
1263
1303
  action since we're redirecting to the `index` action.
1264
1304
 
1265
1305
  Finally, add a 'Destroy' link to your `index` action template
1266
- (`app/views/posts/index.html.erb`) to wrap everything
1306
+ (`app/views/articles/index.html.erb`) to wrap everything
1267
1307
  together.
1268
1308
 
1269
1309
  ```html+erb
1270
- <h1>Listing Posts</h1>
1271
- <%= link_to 'New post', new_post_path %>
1310
+ <h1>Listing Articles</h1>
1311
+ <%= link_to 'New article', new_article_path %>
1272
1312
  <table>
1273
1313
  <tr>
1274
1314
  <th>Title</th>
@@ -1276,13 +1316,13 @@ together.
1276
1316
  <th colspan="3"></th>
1277
1317
  </tr>
1278
1318
 
1279
- <% @posts.each do |post| %>
1319
+ <% @articles.each do |article| %>
1280
1320
  <tr>
1281
- <td><%= post.title %></td>
1282
- <td><%= post.text %></td>
1283
- <td><%= link_to 'Show', post_path(post) %></td>
1284
- <td><%= link_to 'Edit', edit_post_path(post) %></td>
1285
- <td><%= link_to 'Destroy', post_path(post),
1321
+ <td><%= article.title %></td>
1322
+ <td><%= article.text %></td>
1323
+ <td><%= link_to 'Show', article_path(article) %></td>
1324
+ <td><%= link_to 'Edit', edit_article_path(article) %></td>
1325
+ <td><%= link_to 'Destroy', article_path(article),
1286
1326
  method: :delete, data: { confirm: 'Are you sure?' } %></td>
1287
1327
  </tr>
1288
1328
  <% end %>
@@ -1301,7 +1341,7 @@ Without this file, the confirmation dialog box wouldn't appear.
1301
1341
  ![Confirm Dialog](images/getting_started/confirm_dialog.png)
1302
1342
 
1303
1343
  Congratulations, you can now create, show, list, update and destroy
1304
- posts.
1344
+ articles.
1305
1345
 
1306
1346
  TIP: In general, Rails encourages the use of resources objects in place
1307
1347
  of declaring routes manually.
@@ -1312,23 +1352,23 @@ Adding a Second Model
1312
1352
  ---------------------
1313
1353
 
1314
1354
  It's time to add a second model to the application. The second model will handle
1315
- comments on posts.
1355
+ comments on articles.
1316
1356
 
1317
1357
  ### Generating a Model
1318
1358
 
1319
1359
  We're going to see the same generator that we used before when creating
1320
- the `Post` model. This time we'll create a `Comment` model to hold
1321
- reference of post comments. Run this command in your terminal:
1360
+ the `Article` model. This time we'll create a `Comment` model to hold
1361
+ reference of article comments. Run this command in your terminal:
1322
1362
 
1323
1363
  ```bash
1324
- $ rails generate model Comment commenter:string body:text post:references
1364
+ $ rails generate model Comment commenter:string body:text article:references
1325
1365
  ```
1326
1366
 
1327
1367
  This command will generate four files:
1328
1368
 
1329
1369
  | File | Purpose |
1330
1370
  | -------------------------------------------- | ------------------------------------------------------------------------------------------------------ |
1331
- | db/migrate/20100207235629_create_comments.rb | Migration to create the comments table in your database (your name will include a different timestamp) |
1371
+ | db/migrate/20140120201010_create_comments.rb | Migration to create the comments table in your database (your name will include a different timestamp) |
1332
1372
  | app/models/comment.rb | The Comment model |
1333
1373
  | test/models/comment_test.rb | Testing harness for the comments model |
1334
1374
  | test/fixtures/comments.yml | Sample comments for use in testing |
@@ -1337,12 +1377,12 @@ First, take a look at `app/models/comment.rb`:
1337
1377
 
1338
1378
  ```ruby
1339
1379
  class Comment < ActiveRecord::Base
1340
- belongs_to :post
1380
+ belongs_to :article
1341
1381
  end
1342
1382
  ```
1343
1383
 
1344
- This is very similar to the `Post` model that you saw earlier. The difference
1345
- is the line `belongs_to :post`, which sets up an Active Record _association_.
1384
+ This is very similar to the `Article` model that you saw earlier. The difference
1385
+ is the line `belongs_to :article`, which sets up an Active Record _association_.
1346
1386
  You'll learn a little about associations in the next section of this guide.
1347
1387
 
1348
1388
  In addition to the model, Rails has also made a migration to create the
@@ -1354,7 +1394,9 @@ class CreateComments < ActiveRecord::Migration
1354
1394
  create_table :comments do |t|
1355
1395
  t.string :commenter
1356
1396
  t.text :body
1357
- t.references :post, index: true
1397
+
1398
+ # this line adds an integer column called `article_id`.
1399
+ t.references :article, index: true
1358
1400
 
1359
1401
  t.timestamps
1360
1402
  end
@@ -1383,57 +1425,59 @@ run against the current database, so in this case you will just see:
1383
1425
  ### Associating Models
1384
1426
 
1385
1427
  Active Record associations let you easily declare the relationship between two
1386
- models. In the case of comments and posts, you could write out the relationships
1387
- this way:
1428
+ models. In the case of comments and articles, you could write out the
1429
+ relationships this way:
1388
1430
 
1389
- * Each comment belongs to one post.
1390
- * One post can have many comments.
1431
+ * Each comment belongs to one article.
1432
+ * One article can have many comments.
1391
1433
 
1392
1434
  In fact, this is very close to the syntax that Rails uses to declare this
1393
1435
  association. You've already seen the line of code inside the `Comment` model
1394
- (app/models/comment.rb) that makes each comment belong to a Post:
1436
+ (app/models/comment.rb) that makes each comment belong to an Article:
1395
1437
 
1396
1438
  ```ruby
1397
1439
  class Comment < ActiveRecord::Base
1398
- belongs_to :post
1440
+ belongs_to :article
1399
1441
  end
1400
1442
  ```
1401
1443
 
1402
- You'll need to edit `app/models/post.rb` to add the other side of the association:
1444
+ You'll need to edit `app/models/article.rb` to add the other side of the
1445
+ association:
1403
1446
 
1404
1447
  ```ruby
1405
- class Post < ActiveRecord::Base
1448
+ class Article < ActiveRecord::Base
1406
1449
  has_many :comments
1407
1450
  validates :title, presence: true,
1408
1451
  length: { minimum: 5 }
1409
- [...]
1410
1452
  end
1411
1453
  ```
1412
1454
 
1413
1455
  These two declarations enable a good bit of automatic behavior. For example, if
1414
- you have an instance variable `@post` containing a post, you can retrieve all
1415
- the comments belonging to that post as an array using `@post.comments`.
1456
+ you have an instance variable `@article` containing an article, you can retrieve
1457
+ all the comments belonging to that article as an array using
1458
+ `@article.comments`.
1416
1459
 
1417
1460
  TIP: For more information on Active Record associations, see the [Active Record
1418
1461
  Associations](association_basics.html) guide.
1419
1462
 
1420
1463
  ### Adding a Route for Comments
1421
1464
 
1422
- As with the `welcome` controller, we will need to add a route so that Rails knows
1423
- where we would like to navigate to see `comments`. Open up the
1465
+ As with the `welcome` controller, we will need to add a route so that Rails
1466
+ knows where we would like to navigate to see `comments`. Open up the
1424
1467
  `config/routes.rb` file again, and edit it as follows:
1425
1468
 
1426
1469
  ```ruby
1427
- resources :posts do
1470
+ resources :articles do
1428
1471
  resources :comments
1429
1472
  end
1430
1473
  ```
1431
1474
 
1432
- This creates `comments` as a _nested resource_ within `posts`. This is another
1433
- part of capturing the hierarchical relationship that exists between posts and
1434
- comments.
1475
+ This creates `comments` as a _nested resource_ within `articles`. This is
1476
+ another part of capturing the hierarchical relationship that exists between
1477
+ articles and comments.
1435
1478
 
1436
- TIP: For more information on routing, see the [Rails Routing](routing.html) guide.
1479
+ TIP: For more information on routing, see the [Rails Routing](routing.html)
1480
+ guide.
1437
1481
 
1438
1482
  ### Generating a Controller
1439
1483
 
@@ -1457,27 +1501,27 @@ This creates six files and one empty directory:
1457
1501
  | app/assets/stylesheets/comment.css.scss | Cascading style sheet for the controller |
1458
1502
 
1459
1503
  Like with any blog, our readers will create their comments directly after
1460
- reading the post, and once they have added their comment, will be sent back to
1461
- the post show page to see their comment now listed. Due to this, our
1504
+ reading the article, and once they have added their comment, will be sent back
1505
+ to the article show page to see their comment now listed. Due to this, our
1462
1506
  `CommentsController` is there to provide a method to create comments and delete
1463
1507
  spam comments when they arrive.
1464
1508
 
1465
- So first, we'll wire up the Post show template
1466
- (`app/views/posts/show.html.erb`) to let us make a new comment:
1509
+ So first, we'll wire up the Article show template
1510
+ (`app/views/articles/show.html.erb`) to let us make a new comment:
1467
1511
 
1468
1512
  ```html+erb
1469
1513
  <p>
1470
1514
  <strong>Title:</strong>
1471
- <%= @post.title %>
1515
+ <%= @article.title %>
1472
1516
  </p>
1473
1517
 
1474
1518
  <p>
1475
1519
  <strong>Text:</strong>
1476
- <%= @post.text %>
1520
+ <%= @article.text %>
1477
1521
  </p>
1478
1522
 
1479
1523
  <h2>Add a comment:</h2>
1480
- <%= form_for([@post, @post.comments.build]) do |f| %>
1524
+ <%= form_for([@article, @article.comments.build]) do |f| %>
1481
1525
  <p>
1482
1526
  <%= f.label :commenter %><br>
1483
1527
  <%= f.text_field :commenter %>
@@ -1491,22 +1535,22 @@ So first, we'll wire up the Post show template
1491
1535
  </p>
1492
1536
  <% end %>
1493
1537
 
1494
- <%= link_to 'Back', posts_path %>
1495
- | <%= link_to 'Edit', edit_post_path(@post) %>
1538
+ <%= link_to 'Back', articles_path %>
1539
+ | <%= link_to 'Edit', edit_article_path(@article) %>
1496
1540
  ```
1497
1541
 
1498
- This adds a form on the `Post` show page that creates a new comment by
1542
+ This adds a form on the `Article` show page that creates a new comment by
1499
1543
  calling the `CommentsController` `create` action. The `form_for` call here uses
1500
- an array, which will build a nested route, such as `/posts/1/comments`.
1544
+ an array, which will build a nested route, such as `/articles/1/comments`.
1501
1545
 
1502
1546
  Let's wire up the `create` in `app/controllers/comments_controller.rb`:
1503
1547
 
1504
1548
  ```ruby
1505
1549
  class CommentsController < ApplicationController
1506
1550
  def create
1507
- @post = Post.find(params[:post_id])
1508
- @comment = @post.comments.create(comment_params)
1509
- redirect_to post_path(@post)
1551
+ @article = Article.find(params[:article_id])
1552
+ @comment = @article.comments.create(comment_params)
1553
+ redirect_to article_path(@article)
1510
1554
  end
1511
1555
 
1512
1556
  private
@@ -1516,35 +1560,36 @@ class CommentsController < ApplicationController
1516
1560
  end
1517
1561
  ```
1518
1562
 
1519
- You'll see a bit more complexity here than you did in the controller for posts.
1520
- That's a side-effect of the nesting that you've set up. Each request for a
1521
- comment has to keep track of the post to which the comment is attached, thus the
1522
- initial call to the `find` method of the `Post` model to get the post in question.
1563
+ You'll see a bit more complexity here than you did in the controller for
1564
+ articles. That's a side-effect of the nesting that you've set up. Each request
1565
+ for a comment has to keep track of the article to which the comment is attached,
1566
+ thus the initial call to the `find` method of the `Article` model to get the
1567
+ article in question.
1523
1568
 
1524
1569
  In addition, the code takes advantage of some of the methods available for an
1525
- association. We use the `create` method on `@post.comments` to create and save
1526
- the comment. This will automatically link the comment so that it belongs to that
1527
- particular post.
1570
+ association. We use the `create` method on `@article.comments` to create and
1571
+ save the comment. This will automatically link the comment so that it belongs to
1572
+ that particular article.
1528
1573
 
1529
- Once we have made the new comment, we send the user back to the original post
1530
- using the `post_path(@post)` helper. As we have already seen, this calls the
1531
- `show` action of the `PostsController` which in turn renders the `show.html.erb`
1532
- template. This is where we want the comment to show, so let's add that to the
1533
- `app/views/posts/show.html.erb`.
1574
+ Once we have made the new comment, we send the user back to the original article
1575
+ using the `article_path(@article)` helper. As we have already seen, this calls
1576
+ the `show` action of the `ArticlesController` which in turn renders the
1577
+ `show.html.erb` template. This is where we want the comment to show, so let's
1578
+ add that to the `app/views/articles/show.html.erb`.
1534
1579
 
1535
1580
  ```html+erb
1536
1581
  <p>
1537
1582
  <strong>Title:</strong>
1538
- <%= @post.title %>
1583
+ <%= @article.title %>
1539
1584
  </p>
1540
1585
 
1541
1586
  <p>
1542
1587
  <strong>Text:</strong>
1543
- <%= @post.text %>
1588
+ <%= @article.text %>
1544
1589
  </p>
1545
1590
 
1546
1591
  <h2>Comments</h2>
1547
- <% @post.comments.each do |comment| %>
1592
+ <% @article.comments.each do |comment| %>
1548
1593
  <p>
1549
1594
  <strong>Commenter:</strong>
1550
1595
  <%= comment.commenter %>
@@ -1557,7 +1602,7 @@ template. This is where we want the comment to show, so let's add that to the
1557
1602
  <% end %>
1558
1603
 
1559
1604
  <h2>Add a comment:</h2>
1560
- <%= form_for([@post, @post.comments.build]) do |f| %>
1605
+ <%= form_for([@article, @article.comments.build]) do |f| %>
1561
1606
  <p>
1562
1607
  <%= f.label :commenter %><br>
1563
1608
  <%= f.text_field :commenter %>
@@ -1571,26 +1616,26 @@ template. This is where we want the comment to show, so let's add that to the
1571
1616
  </p>
1572
1617
  <% end %>
1573
1618
 
1574
- <%= link_to 'Edit Post', edit_post_path(@post) %> |
1575
- <%= link_to 'Back to Posts', posts_path %>
1619
+ <%= link_to 'Edit Article', edit_article_path(@article) %> |
1620
+ <%= link_to 'Back to Articles', articles_path %>
1576
1621
  ```
1577
1622
 
1578
- Now you can add posts and comments to your blog and have them show up in the
1623
+ Now you can add articles and comments to your blog and have them show up in the
1579
1624
  right places.
1580
1625
 
1581
- ![Post with Comments](images/getting_started/post_with_comments.png)
1626
+ ![Article with Comments](images/getting_started/article_with_comments.png)
1582
1627
 
1583
1628
  Refactoring
1584
1629
  -----------
1585
1630
 
1586
- Now that we have posts and comments working, take a look at the
1587
- `app/views/posts/show.html.erb` template. It is getting long and awkward. We can
1588
- use partials to clean it up.
1631
+ Now that we have articles and comments working, take a look at the
1632
+ `app/views/articles/show.html.erb` template. It is getting long and awkward. We
1633
+ can use partials to clean it up.
1589
1634
 
1590
1635
  ### Rendering Partial Collections
1591
1636
 
1592
- First, we will make a comment partial to extract showing all the comments for the
1593
- post. Create the file `app/views/comments/_comment.html.erb` and put the
1637
+ First, we will make a comment partial to extract showing all the comments for
1638
+ the article. Create the file `app/views/comments/_comment.html.erb` and put the
1594
1639
  following into it:
1595
1640
 
1596
1641
  ```html+erb
@@ -1605,25 +1650,25 @@ following into it:
1605
1650
  </p>
1606
1651
  ```
1607
1652
 
1608
- Then you can change `app/views/posts/show.html.erb` to look like the
1653
+ Then you can change `app/views/articles/show.html.erb` to look like the
1609
1654
  following:
1610
1655
 
1611
1656
  ```html+erb
1612
1657
  <p>
1613
1658
  <strong>Title:</strong>
1614
- <%= @post.title %>
1659
+ <%= @article.title %>
1615
1660
  </p>
1616
1661
 
1617
1662
  <p>
1618
1663
  <strong>Text:</strong>
1619
- <%= @post.text %>
1664
+ <%= @article.text %>
1620
1665
  </p>
1621
1666
 
1622
1667
  <h2>Comments</h2>
1623
- <%= render @post.comments %>
1668
+ <%= render @article.comments %>
1624
1669
 
1625
1670
  <h2>Add a comment:</h2>
1626
- <%= form_for([@post, @post.comments.build]) do |f| %>
1671
+ <%= form_for([@article, @article.comments.build]) do |f| %>
1627
1672
  <p>
1628
1673
  <%= f.label :commenter %><br>
1629
1674
  <%= f.text_field :commenter %>
@@ -1637,13 +1682,13 @@ following:
1637
1682
  </p>
1638
1683
  <% end %>
1639
1684
 
1640
- <%= link_to 'Edit Post', edit_post_path(@post) %> |
1641
- <%= link_to 'Back to Posts', posts_path %>
1685
+ <%= link_to 'Edit Article', edit_article_path(@article) %> |
1686
+ <%= link_to 'Back to Articles', articles_path %>
1642
1687
  ```
1643
1688
 
1644
1689
  This will now render the partial in `app/views/comments/_comment.html.erb` once
1645
- for each comment that is in the `@post.comments` collection. As the `render`
1646
- method iterates over the `@post.comments` collection, it assigns each
1690
+ for each comment that is in the `@article.comments` collection. As the `render`
1691
+ method iterates over the `@article.comments` collection, it assigns each
1647
1692
  comment to a local variable named the same as the partial, in this case
1648
1693
  `comment` which is then available in the partial for us to show.
1649
1694
 
@@ -1653,7 +1698,7 @@ Let us also move that new comment section out to its own partial. Again, you
1653
1698
  create a file `app/views/comments/_form.html.erb` containing:
1654
1699
 
1655
1700
  ```html+erb
1656
- <%= form_for([@post, @post.comments.build]) do |f| %>
1701
+ <%= form_for([@article, @article.comments.build]) do |f| %>
1657
1702
  <p>
1658
1703
  <%= f.label :commenter %><br>
1659
1704
  <%= f.text_field :commenter %>
@@ -1668,27 +1713,27 @@ create a file `app/views/comments/_form.html.erb` containing:
1668
1713
  <% end %>
1669
1714
  ```
1670
1715
 
1671
- Then you make the `app/views/posts/show.html.erb` look like the following:
1716
+ Then you make the `app/views/articles/show.html.erb` look like the following:
1672
1717
 
1673
1718
  ```html+erb
1674
1719
  <p>
1675
1720
  <strong>Title:</strong>
1676
- <%= @post.title %>
1721
+ <%= @article.title %>
1677
1722
  </p>
1678
1723
 
1679
1724
  <p>
1680
1725
  <strong>Text:</strong>
1681
- <%= @post.text %>
1726
+ <%= @article.text %>
1682
1727
  </p>
1683
1728
 
1684
1729
  <h2>Comments</h2>
1685
- <%= render @post.comments %>
1730
+ <%= render @article.comments %>
1686
1731
 
1687
1732
  <h2>Add a comment:</h2>
1688
1733
  <%= render "comments/form" %>
1689
1734
 
1690
- <%= link_to 'Edit Post', edit_post_path(@post) %> |
1691
- <%= link_to 'Back to Posts', posts_path %>
1735
+ <%= link_to 'Edit Article', edit_article_path(@article) %> |
1736
+ <%= link_to 'Back to Articles', articles_path %>
1692
1737
  ```
1693
1738
 
1694
1739
  The second render just defines the partial template we want to render,
@@ -1696,15 +1741,15 @@ The second render just defines the partial template we want to render,
1696
1741
  string and realize that you want to render the `_form.html.erb` file in
1697
1742
  the `app/views/comments` directory.
1698
1743
 
1699
- The `@post` object is available to any partials rendered in the view because we
1700
- defined it as an instance variable.
1744
+ The `@article` object is available to any partials rendered in the view because
1745
+ we defined it as an instance variable.
1701
1746
 
1702
1747
  Deleting Comments
1703
1748
  -----------------
1704
1749
 
1705
1750
  Another important feature of a blog is being able to delete spam comments. To do
1706
- this, we need to implement a link of some sort in the view and a `DELETE` action
1707
- in the `CommentsController`.
1751
+ this, we need to implement a link of some sort in the view and a `destroy`
1752
+ action in the `CommentsController`.
1708
1753
 
1709
1754
  So first, let's add the delete link in the
1710
1755
  `app/views/comments/_comment.html.erb` partial:
@@ -1721,30 +1766,30 @@ So first, let's add the delete link in the
1721
1766
  </p>
1722
1767
 
1723
1768
  <p>
1724
- <%= link_to 'Destroy Comment', [comment.post, comment],
1769
+ <%= link_to 'Destroy Comment', [comment.article, comment],
1725
1770
  method: :delete,
1726
1771
  data: { confirm: 'Are you sure?' } %>
1727
1772
  </p>
1728
1773
  ```
1729
1774
 
1730
1775
  Clicking this new "Destroy Comment" link will fire off a `DELETE
1731
- /posts/:post_id/comments/:id` to our `CommentsController`, which can then use
1732
- this to find the comment we want to delete, so let's add a destroy action to our
1733
- controller (`app/controllers/comments_controller.rb`):
1776
+ /articles/:article_id/comments/:id` to our `CommentsController`, which can then
1777
+ use this to find the comment we want to delete, so let's add a `destroy` action
1778
+ to our controller (`app/controllers/comments_controller.rb`):
1734
1779
 
1735
1780
  ```ruby
1736
1781
  class CommentsController < ApplicationController
1737
1782
  def create
1738
- @post = Post.find(params[:post_id])
1739
- @comment = @post.comments.create(comment_params)
1740
- redirect_to post_path(@post)
1783
+ @article = Article.find(params[:article_id])
1784
+ @comment = @article.comments.create(comment_params)
1785
+ redirect_to article_path(@article)
1741
1786
  end
1742
1787
 
1743
1788
  def destroy
1744
- @post = Post.find(params[:post_id])
1745
- @comment = @post.comments.find(params[:id])
1789
+ @article = Article.find(params[:article_id])
1790
+ @comment = @article.comments.find(params[:id])
1746
1791
  @comment.destroy
1747
- redirect_to post_path(@post)
1792
+ redirect_to article_path(@article)
1748
1793
  end
1749
1794
 
1750
1795
  private
@@ -1754,24 +1799,23 @@ class CommentsController < ApplicationController
1754
1799
  end
1755
1800
  ```
1756
1801
 
1757
- The `destroy` action will find the post we are looking at, locate the comment
1758
- within the `@post.comments` collection, and then remove it from the
1759
- database and send us back to the show action for the post.
1802
+ The `destroy` action will find the article we are looking at, locate the comment
1803
+ within the `@article.comments` collection, and then remove it from the
1804
+ database and send us back to the show action for the article.
1760
1805
 
1761
1806
 
1762
1807
  ### Deleting Associated Objects
1763
1808
 
1764
- If you delete a post then its associated comments will also need to be deleted.
1765
- Otherwise they would simply occupy space in the database. Rails allows you to
1766
- use the `dependent` option of an association to achieve this. Modify the Post
1767
- model, `app/models/post.rb`, as follows:
1809
+ If you delete an article then its associated comments will also need to be
1810
+ deleted. Otherwise they would simply occupy space in the database. Rails allows
1811
+ you to use the `dependent` option of an association to achieve this. Modify the
1812
+ Article model, `app/models/article.rb`, as follows:
1768
1813
 
1769
1814
  ```ruby
1770
- class Post < ActiveRecord::Base
1815
+ class Article < ActiveRecord::Base
1771
1816
  has_many :comments, dependent: :destroy
1772
1817
  validates :title, presence: true,
1773
1818
  length: { minimum: 5 }
1774
- [...]
1775
1819
  end
1776
1820
  ```
1777
1821
 
@@ -1781,33 +1825,34 @@ Security
1781
1825
  ### Basic Authentication
1782
1826
 
1783
1827
  If you were to publish your blog online, anybody would be able to add, edit and
1784
- delete posts or delete comments.
1828
+ delete articles or delete comments.
1785
1829
 
1786
1830
  Rails provides a very simple HTTP authentication system that will work nicely in
1787
1831
  this situation.
1788
1832
 
1789
- In the `PostsController` we need to have a way to block access to the various
1833
+ In the `ArticlesController` we need to have a way to block access to the various
1790
1834
  actions if the person is not authenticated, here we can use the Rails
1791
1835
  `http_basic_authenticate_with` method, allowing access to the requested
1792
1836
  action if that method allows it.
1793
1837
 
1794
1838
  To use the authentication system, we specify it at the top of our
1795
- `PostsController`, in this case, we want the user to be authenticated on every
1796
- action, except for `index` and `show`, so we write that in `app/controllers/posts_controller.rb`:
1839
+ `ArticlesController`, in this case, we want the user to be authenticated on
1840
+ every action, except for `index` and `show`, so we write that in
1841
+ `app/controllers/articles_controller.rb`:
1797
1842
 
1798
1843
  ```ruby
1799
- class PostsController < ApplicationController
1844
+ class ArticlesController < ApplicationController
1800
1845
 
1801
1846
  http_basic_authenticate_with name: "dhh", password: "secret", except: [:index, :show]
1802
1847
 
1803
1848
  def index
1804
- @posts = Post.all
1849
+ @articles = Article.all
1805
1850
  end
1806
1851
 
1807
1852
  # snipped for brevity
1808
1853
  ```
1809
1854
 
1810
- We also only want to allow authenticated users to delete comments, so in the
1855
+ We also want to allow only authenticated users to delete comments, so in the
1811
1856
  `CommentsController` (`app/controllers/comments_controller.rb`) we write:
1812
1857
 
1813
1858
  ```ruby
@@ -1816,21 +1861,22 @@ class CommentsController < ApplicationController
1816
1861
  http_basic_authenticate_with name: "dhh", password: "secret", only: :destroy
1817
1862
 
1818
1863
  def create
1819
- @post = Post.find(params[:post_id])
1864
+ @article = Article.find(params[:article_id])
1820
1865
  ...
1821
1866
  end
1822
1867
 
1823
1868
  # snipped for brevity
1824
1869
  ```
1825
1870
 
1826
- Now if you try to create a new post, you will be greeted with a basic HTTP
1871
+ Now if you try to create a new article, you will be greeted with a basic HTTP
1827
1872
  Authentication challenge
1828
1873
 
1829
1874
  ![Basic HTTP Authentication Challenge](images/getting_started/challenge.png)
1830
1875
 
1831
1876
  Other authentication methods are available for Rails applications. Two popular
1832
- authentication add-ons for Rails are the [Devise](https://github.com/plataformatec/devise)
1833
- rails engine and the [Authlogic](https://github.com/binarylogic/authlogic) gem,
1877
+ authentication add-ons for Rails are the
1878
+ [Devise](https://github.com/plataformatec/devise) rails engine and
1879
+ the [Authlogic](https://github.com/binarylogic/authlogic) gem,
1834
1880
  along with a number of others.
1835
1881
 
1836
1882
 
@@ -1886,15 +1932,16 @@ cannot be automatically detected by Rails and corrected.
1886
1932
 
1887
1933
  Two very common sources of data that are not UTF-8:
1888
1934
 
1889
- * Your text editor: Most text editors (such as TextMate), default to saving files as
1890
- UTF-8. If your text editor does not, this can result in special characters that you
1891
- enter in your templates (such as é) to appear as a diamond with a question mark inside
1892
- in the browser. This also applies to your i18n translation files.
1893
- Most editors that do not already default to UTF-8 (such as some versions of
1894
- Dreamweaver) offer a way to change the default to UTF-8. Do so.
1895
- * Your database: Rails defaults to converting data from your database into UTF-8 at
1896
- the boundary. However, if your database is not using UTF-8 internally, it may not
1897
- be able to store all characters that your users enter. For instance, if your database
1898
- is using Latin-1 internally, and your user enters a Russian, Hebrew, or Japanese
1899
- character, the data will be lost forever once it enters the database. If possible,
1900
- use UTF-8 as the internal storage of your database.
1935
+ * Your text editor: Most text editors (such as TextMate), default to saving
1936
+ files as UTF-8. If your text editor does not, this can result in special
1937
+ characters that you enter in your templates (such as é) to appear as a diamond
1938
+ with a question mark inside in the browser. This also applies to your i18n
1939
+ translation files. Most editors that do not already default to UTF-8 (such as
1940
+ some versions of Dreamweaver) offer a way to change the default to UTF-8. Do
1941
+ so.
1942
+ * Your database: Rails defaults to converting data from your database into UTF-8
1943
+ at the boundary. However, if your database is not using UTF-8 internally, it
1944
+ may not be able to store all characters that your users enter. For instance,
1945
+ if your database is using Latin-1 internally, and your user enters a Russian,
1946
+ Hebrew, or Japanese character, the data will be lost forever once it enters
1947
+ the database. If possible, use UTF-8 as the internal storage of your database.