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