rails 4.2.11 → 5.0.0
Sign up to get free protection for your applications and to get access to all the features.
- checksums.yaml +5 -5
- data/README.md +14 -10
- metadata +37 -238
- data/guides/CHANGELOG.md +0 -98
- data/guides/Rakefile +0 -92
- data/guides/assets/images/akshaysurve.jpg +0 -0
- data/guides/assets/images/belongs_to.png +0 -0
- data/guides/assets/images/book_icon.gif +0 -0
- data/guides/assets/images/bullet.gif +0 -0
- data/guides/assets/images/chapters_icon.gif +0 -0
- data/guides/assets/images/check_bullet.gif +0 -0
- data/guides/assets/images/credits_pic_blank.gif +0 -0
- data/guides/assets/images/csrf.png +0 -0
- data/guides/assets/images/edge_badge.png +0 -0
- data/guides/assets/images/favicon.ico +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/grey_bullet.gif +0 -0
- data/guides/assets/images/habtm.png +0 -0
- data/guides/assets/images/has_many.png +0 -0
- data/guides/assets/images/has_many_through.png +0 -0
- data/guides/assets/images/has_one.png +0 -0
- data/guides/assets/images/has_one_through.png +0 -0
- data/guides/assets/images/header_backdrop.png +0 -0
- data/guides/assets/images/header_tile.gif +0 -0
- data/guides/assets/images/i18n/demo_html_safe.png +0 -0
- data/guides/assets/images/i18n/demo_localized_pirate.png +0 -0
- data/guides/assets/images/i18n/demo_translated_en.png +0 -0
- data/guides/assets/images/i18n/demo_translated_pirate.png +0 -0
- data/guides/assets/images/i18n/demo_translation_missing.png +0 -0
- data/guides/assets/images/i18n/demo_untranslated.png +0 -0
- data/guides/assets/images/icons/README +0 -5
- data/guides/assets/images/icons/callouts/1.png +0 -0
- data/guides/assets/images/icons/callouts/10.png +0 -0
- 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/14.png +0 -0
- data/guides/assets/images/icons/callouts/15.png +0 -0
- data/guides/assets/images/icons/callouts/2.png +0 -0
- data/guides/assets/images/icons/callouts/3.png +0 -0
- data/guides/assets/images/icons/callouts/4.png +0 -0
- data/guides/assets/images/icons/callouts/5.png +0 -0
- data/guides/assets/images/icons/callouts/6.png +0 -0
- data/guides/assets/images/icons/callouts/7.png +0 -0
- data/guides/assets/images/icons/callouts/8.png +0 -0
- data/guides/assets/images/icons/callouts/9.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/icons/home.png +0 -0
- data/guides/assets/images/icons/important.png +0 -0
- data/guides/assets/images/icons/next.png +0 -0
- data/guides/assets/images/icons/note.png +0 -0
- data/guides/assets/images/icons/prev.png +0 -0
- data/guides/assets/images/icons/tip.png +0 -0
- data/guides/assets/images/icons/up.png +0 -0
- data/guides/assets/images/icons/warning.png +0 -0
- data/guides/assets/images/nav_arrow.gif +0 -0
- data/guides/assets/images/oscardelben.jpg +0 -0
- data/guides/assets/images/polymorphic.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/rails_guides_logo.gif +0 -0
- data/guides/assets/images/rails_logo_remix.gif +0 -0
- data/guides/assets/images/session_fixation.png +0 -0
- data/guides/assets/images/tab_grey.gif +0 -0
- data/guides/assets/images/tab_info.gif +0 -0
- data/guides/assets/images/tab_note.gif +0 -0
- data/guides/assets/images/tab_red.gif +0 -0
- data/guides/assets/images/tab_yellow.gif +0 -0
- data/guides/assets/images/tab_yellow.png +0 -0
- data/guides/assets/images/vijaydev.jpg +0 -0
- data/guides/assets/javascripts/guides.js +0 -59
- data/guides/assets/javascripts/jquery.min.js +0 -4
- data/guides/assets/javascripts/responsive-tables.js +0 -43
- data/guides/assets/javascripts/syntaxhighlighter/shBrushAS3.js +0 -59
- data/guides/assets/javascripts/syntaxhighlighter/shBrushAppleScript.js +0 -75
- data/guides/assets/javascripts/syntaxhighlighter/shBrushBash.js +0 -59
- data/guides/assets/javascripts/syntaxhighlighter/shBrushCSharp.js +0 -65
- data/guides/assets/javascripts/syntaxhighlighter/shBrushColdFusion.js +0 -100
- data/guides/assets/javascripts/syntaxhighlighter/shBrushCpp.js +0 -97
- data/guides/assets/javascripts/syntaxhighlighter/shBrushCss.js +0 -91
- data/guides/assets/javascripts/syntaxhighlighter/shBrushDelphi.js +0 -55
- data/guides/assets/javascripts/syntaxhighlighter/shBrushDiff.js +0 -41
- data/guides/assets/javascripts/syntaxhighlighter/shBrushErlang.js +0 -52
- data/guides/assets/javascripts/syntaxhighlighter/shBrushGroovy.js +0 -67
- data/guides/assets/javascripts/syntaxhighlighter/shBrushJScript.js +0 -52
- data/guides/assets/javascripts/syntaxhighlighter/shBrushJava.js +0 -57
- data/guides/assets/javascripts/syntaxhighlighter/shBrushJavaFX.js +0 -58
- data/guides/assets/javascripts/syntaxhighlighter/shBrushPerl.js +0 -72
- data/guides/assets/javascripts/syntaxhighlighter/shBrushPhp.js +0 -88
- data/guides/assets/javascripts/syntaxhighlighter/shBrushPlain.js +0 -33
- data/guides/assets/javascripts/syntaxhighlighter/shBrushPowerShell.js +0 -74
- data/guides/assets/javascripts/syntaxhighlighter/shBrushPython.js +0 -64
- data/guides/assets/javascripts/syntaxhighlighter/shBrushRuby.js +0 -55
- data/guides/assets/javascripts/syntaxhighlighter/shBrushSass.js +0 -94
- data/guides/assets/javascripts/syntaxhighlighter/shBrushScala.js +0 -51
- data/guides/assets/javascripts/syntaxhighlighter/shBrushSql.js +0 -66
- data/guides/assets/javascripts/syntaxhighlighter/shBrushVb.js +0 -56
- data/guides/assets/javascripts/syntaxhighlighter/shBrushXml.js +0 -69
- data/guides/assets/javascripts/syntaxhighlighter/shCore.js +0 -17
- data/guides/assets/stylesheets/fixes.css +0 -16
- data/guides/assets/stylesheets/kindle.css +0 -11
- data/guides/assets/stylesheets/main.css +0 -713
- data/guides/assets/stylesheets/print.css +0 -52
- data/guides/assets/stylesheets/reset.css +0 -43
- data/guides/assets/stylesheets/responsive-tables.css +0 -50
- data/guides/assets/stylesheets/style.css +0 -13
- data/guides/assets/stylesheets/syntaxhighlighter/shCore.css +0 -226
- data/guides/assets/stylesheets/syntaxhighlighter/shCoreDefault.css +0 -328
- data/guides/assets/stylesheets/syntaxhighlighter/shCoreDjango.css +0 -331
- data/guides/assets/stylesheets/syntaxhighlighter/shCoreEclipse.css +0 -339
- data/guides/assets/stylesheets/syntaxhighlighter/shCoreEmacs.css +0 -324
- data/guides/assets/stylesheets/syntaxhighlighter/shCoreFadeToGrey.css +0 -328
- data/guides/assets/stylesheets/syntaxhighlighter/shCoreMDUltra.css +0 -324
- data/guides/assets/stylesheets/syntaxhighlighter/shCoreMidnight.css +0 -324
- data/guides/assets/stylesheets/syntaxhighlighter/shCoreRDark.css +0 -324
- data/guides/assets/stylesheets/syntaxhighlighter/shThemeDefault.css +0 -117
- data/guides/assets/stylesheets/syntaxhighlighter/shThemeDjango.css +0 -120
- data/guides/assets/stylesheets/syntaxhighlighter/shThemeEclipse.css +0 -128
- data/guides/assets/stylesheets/syntaxhighlighter/shThemeEmacs.css +0 -113
- data/guides/assets/stylesheets/syntaxhighlighter/shThemeFadeToGrey.css +0 -117
- data/guides/assets/stylesheets/syntaxhighlighter/shThemeMDUltra.css +0 -113
- data/guides/assets/stylesheets/syntaxhighlighter/shThemeMidnight.css +0 -113
- data/guides/assets/stylesheets/syntaxhighlighter/shThemeRDark.css +0 -113
- data/guides/assets/stylesheets/syntaxhighlighter/shThemeRailsGuides.css +0 -116
- data/guides/bug_report_templates/action_controller_gem.rb +0 -47
- data/guides/bug_report_templates/action_controller_master.rb +0 -54
- data/guides/bug_report_templates/active_record_gem.rb +0 -40
- data/guides/bug_report_templates/active_record_master.rb +0 -49
- data/guides/bug_report_templates/generic_gem.rb +0 -15
- data/guides/bug_report_templates/generic_master.rb +0 -26
- data/guides/rails_guides.rb +0 -63
- data/guides/rails_guides/generator.rb +0 -248
- data/guides/rails_guides/helpers.rb +0 -53
- data/guides/rails_guides/indexer.rb +0 -68
- data/guides/rails_guides/kindle.rb +0 -119
- data/guides/rails_guides/levenshtein.rb +0 -37
- data/guides/rails_guides/markdown.rb +0 -167
- data/guides/rails_guides/markdown/renderer.rb +0 -82
- data/guides/source/2_2_release_notes.md +0 -435
- data/guides/source/2_3_release_notes.md +0 -621
- data/guides/source/3_0_release_notes.md +0 -611
- data/guides/source/3_1_release_notes.md +0 -559
- data/guides/source/3_2_release_notes.md +0 -568
- data/guides/source/4_0_release_notes.md +0 -279
- data/guides/source/4_1_release_notes.md +0 -730
- data/guides/source/4_2_release_notes.md +0 -877
- data/guides/source/_license.html.erb +0 -2
- data/guides/source/_welcome.html.erb +0 -23
- data/guides/source/action_controller_overview.md +0 -1192
- data/guides/source/action_mailer_basics.md +0 -757
- data/guides/source/action_view_overview.md +0 -1561
- data/guides/source/active_job_basics.md +0 -339
- data/guides/source/active_model_basics.md +0 -554
- data/guides/source/active_record_basics.md +0 -374
- data/guides/source/active_record_callbacks.md +0 -413
- data/guides/source/active_record_migrations.md +0 -1018
- data/guides/source/active_record_postgresql.md +0 -433
- data/guides/source/active_record_querying.md +0 -1781
- data/guides/source/active_record_validations.md +0 -1179
- data/guides/source/active_support_core_extensions.md +0 -3856
- data/guides/source/active_support_instrumentation.md +0 -488
- data/guides/source/api_documentation_guidelines.md +0 -361
- data/guides/source/asset_pipeline.md +0 -1304
- data/guides/source/association_basics.md +0 -2245
- data/guides/source/autoloading_and_reloading_constants.md +0 -1311
- data/guides/source/caching_with_rails.md +0 -379
- data/guides/source/command_line.md +0 -625
- data/guides/source/configuring.md +0 -1070
- data/guides/source/contributing_to_ruby_on_rails.md +0 -628
- data/guides/source/credits.html.erb +0 -80
- data/guides/source/debugging_rails_applications.md +0 -861
- data/guides/source/development_dependencies_install.md +0 -289
- data/guides/source/documents.yaml +0 -205
- data/guides/source/engines.md +0 -1412
- data/guides/source/form_helpers.md +0 -1024
- data/guides/source/generators.md +0 -676
- data/guides/source/getting_started.md +0 -2086
- data/guides/source/i18n.md +0 -1087
- data/guides/source/index.html.erb +0 -28
- data/guides/source/initialization.md +0 -704
- data/guides/source/kindle/copyright.html.erb +0 -1
- data/guides/source/kindle/layout.html.erb +0 -27
- data/guides/source/kindle/rails_guides.opf.erb +0 -52
- data/guides/source/kindle/toc.html.erb +0 -24
- data/guides/source/kindle/toc.ncx.erb +0 -64
- data/guides/source/kindle/welcome.html.erb +0 -5
- data/guides/source/layout.html.erb +0 -140
- data/guides/source/layouts_and_rendering.md +0 -1226
- data/guides/source/maintenance_policy.md +0 -78
- data/guides/source/nested_model_forms.md +0 -228
- data/guides/source/plugins.md +0 -444
- data/guides/source/rails_application_templates.md +0 -266
- data/guides/source/rails_on_rack.md +0 -335
- data/guides/source/routing.md +0 -1155
- data/guides/source/ruby_on_rails_guides_guidelines.md +0 -127
- data/guides/source/security.md +0 -1024
- data/guides/source/testing.md +0 -1132
- data/guides/source/upgrading_ruby_on_rails.md +0 -1186
- data/guides/source/working_with_javascript_in_rails.md +0 -407
- data/guides/w3c_validator.rb +0 -97
@@ -1,2086 +0,0 @@
|
|
1
|
-
Getting Started with Rails
|
2
|
-
==========================
|
3
|
-
|
4
|
-
This guide covers getting up and running with Ruby on Rails.
|
5
|
-
|
6
|
-
After reading this guide, you will know:
|
7
|
-
|
8
|
-
* How to install Rails, create a new Rails application, and connect your
|
9
|
-
application to a database.
|
10
|
-
* The general layout of a Rails application.
|
11
|
-
* The basic principles of MVC (Model, View, Controller) and RESTful design.
|
12
|
-
* How to quickly generate the starting pieces of a Rails application.
|
13
|
-
|
14
|
-
--------------------------------------------------------------------------------
|
15
|
-
|
16
|
-
Guide Assumptions
|
17
|
-
-----------------
|
18
|
-
|
19
|
-
This guide is designed for beginners who want to get started with a Rails
|
20
|
-
application from scratch. It does not assume that you have any prior experience
|
21
|
-
with Rails. However, to get the most out of it, you need to have some
|
22
|
-
prerequisites installed:
|
23
|
-
|
24
|
-
* The [Ruby](https://www.ruby-lang.org/en/downloads) language version 1.9.3 or newer.
|
25
|
-
* The [RubyGems](https://rubygems.org) packaging system, which is installed with Ruby
|
26
|
-
versions 1.9 and later. To learn more about RubyGems, please read the [RubyGems Guides](http://guides.rubygems.org).
|
27
|
-
* A working installation of the [SQLite3 Database](https://www.sqlite.org).
|
28
|
-
|
29
|
-
Rails is a web application framework running on the Ruby programming language.
|
30
|
-
If you have no prior experience with Ruby, you will find a very steep learning
|
31
|
-
curve diving straight into Rails. There are several curated lists of online resources
|
32
|
-
for learning Ruby:
|
33
|
-
|
34
|
-
* [Official Ruby Programming Language website](https://www.ruby-lang.org/en/documentation/)
|
35
|
-
* [reSRC's List of Free Programming Books](http://resrc.io/list/10/list-of-free-programming-books/#ruby)
|
36
|
-
|
37
|
-
Be aware that some resources, while still excellent, cover versions of Ruby as old as
|
38
|
-
1.6, and commonly 1.8, and will not include some syntax that you will see in day-to-day
|
39
|
-
development with Rails.
|
40
|
-
|
41
|
-
What is Rails?
|
42
|
-
--------------
|
43
|
-
|
44
|
-
Rails is a web application development framework written in the Ruby language.
|
45
|
-
It is designed to make programming web applications easier by making assumptions
|
46
|
-
about what every developer needs to get started. It allows you to write less
|
47
|
-
code while accomplishing more than many other languages and frameworks.
|
48
|
-
Experienced Rails developers also report that it makes web application
|
49
|
-
development more fun.
|
50
|
-
|
51
|
-
Rails is opinionated software. It makes the assumption that there is the "best"
|
52
|
-
way to do things, and it's designed to encourage that way - and in some cases to
|
53
|
-
discourage alternatives. If you learn "The Rails Way" you'll probably discover a
|
54
|
-
tremendous increase in productivity. If you persist in bringing old habits from
|
55
|
-
other languages to your Rails development, and trying to use patterns you
|
56
|
-
learned elsewhere, you may have a less happy experience.
|
57
|
-
|
58
|
-
The Rails philosophy includes two major guiding principles:
|
59
|
-
|
60
|
-
* **Don't Repeat Yourself:** DRY is a principle of software development which
|
61
|
-
states that "Every piece of knowledge must have a single, unambiguous, authoritative
|
62
|
-
representation within a system." By not writing the same information over and over
|
63
|
-
again, our code is more maintainable, more extensible, and less buggy.
|
64
|
-
* **Convention Over Configuration:** Rails has opinions about the best way to do many
|
65
|
-
things in a web application, and defaults to this set of conventions, rather than
|
66
|
-
require that you specify every minutiae through endless configuration files.
|
67
|
-
|
68
|
-
Creating a New Rails Project
|
69
|
-
----------------------------
|
70
|
-
|
71
|
-
The best way to use this guide is to follow each step as it happens, no code or
|
72
|
-
step needed to make this example application has been left out, so you can
|
73
|
-
literally follow along step by step.
|
74
|
-
|
75
|
-
By following along with this guide, you'll create a Rails project called
|
76
|
-
`blog`, a (very) simple weblog. Before you can start building the application,
|
77
|
-
you need to make sure that you have Rails itself installed.
|
78
|
-
|
79
|
-
TIP: The examples below use `$` to represent your terminal prompt in a UNIX-like OS,
|
80
|
-
though it may have been customized to appear differently. If you are using Windows,
|
81
|
-
your prompt will look something like `c:\source_code>`
|
82
|
-
|
83
|
-
### Installing Rails
|
84
|
-
|
85
|
-
Open up a command line prompt. On Mac OS X open Terminal.app, on Windows choose
|
86
|
-
"Run" from your Start menu and type 'cmd.exe'. Any commands prefaced with a
|
87
|
-
dollar sign `$` should be run in the command line. Verify that you have a
|
88
|
-
current version of Ruby installed:
|
89
|
-
|
90
|
-
TIP: A number of tools exist to help you quickly install Ruby and Ruby
|
91
|
-
on Rails on your system. Windows users can use [Rails Installer](http://railsinstaller.org),
|
92
|
-
while Mac OS X users can use [Tokaido](https://github.com/tokaido/tokaidoapp).
|
93
|
-
|
94
|
-
```bash
|
95
|
-
$ ruby -v
|
96
|
-
ruby 2.0.0p353
|
97
|
-
```
|
98
|
-
|
99
|
-
If you don't have Ruby installed have a look at
|
100
|
-
[ruby-lang.org](https://www.ruby-lang.org/en/installation/) for possible ways to
|
101
|
-
install Ruby on your platform.
|
102
|
-
|
103
|
-
Many popular UNIX-like OSes ship with an acceptable version of SQLite3. Windows
|
104
|
-
users and others can find installation instructions at the [SQLite3 website](https://www.sqlite.org).
|
105
|
-
Verify that it is correctly installed and in your PATH:
|
106
|
-
|
107
|
-
```bash
|
108
|
-
$ sqlite3 --version
|
109
|
-
```
|
110
|
-
|
111
|
-
The program should report its version.
|
112
|
-
|
113
|
-
To install Rails, use the `gem install` command provided by RubyGems:
|
114
|
-
|
115
|
-
```bash
|
116
|
-
$ gem install rails
|
117
|
-
```
|
118
|
-
|
119
|
-
To verify that you have everything installed correctly, you should be able to
|
120
|
-
run the following:
|
121
|
-
|
122
|
-
```bash
|
123
|
-
$ rails --version
|
124
|
-
```
|
125
|
-
|
126
|
-
If it says something like "Rails 4.2.1", you are ready to continue.
|
127
|
-
|
128
|
-
### Creating the Blog Application
|
129
|
-
|
130
|
-
Rails comes with a number of scripts called generators that are designed to make
|
131
|
-
your development life easier by creating everything that's necessary to start
|
132
|
-
working on a particular task. One of these is the new application generator,
|
133
|
-
which will provide you with the foundation of a fresh Rails application so that
|
134
|
-
you don't have to write it yourself.
|
135
|
-
|
136
|
-
To use this generator, open a terminal, navigate to a directory where you have
|
137
|
-
rights to create files, and type:
|
138
|
-
|
139
|
-
```bash
|
140
|
-
$ rails new blog
|
141
|
-
```
|
142
|
-
|
143
|
-
This will create a Rails application called Blog in a `blog` directory and
|
144
|
-
install the gem dependencies that are already mentioned in `Gemfile` using
|
145
|
-
`bundle install`.
|
146
|
-
|
147
|
-
TIP: You can see all of the command line options that the Rails application
|
148
|
-
builder accepts by running `rails new -h`.
|
149
|
-
|
150
|
-
After you create the blog application, switch to its folder:
|
151
|
-
|
152
|
-
```bash
|
153
|
-
$ cd blog
|
154
|
-
```
|
155
|
-
|
156
|
-
The `blog` directory has a number of auto-generated files and folders that make
|
157
|
-
up the structure of a Rails application. Most of the work in this tutorial will
|
158
|
-
happen in the `app` folder, but here's a basic rundown on the function of each
|
159
|
-
of the files and folders that Rails created by default:
|
160
|
-
|
161
|
-
| File/Folder | Purpose |
|
162
|
-
| ----------- | ------- |
|
163
|
-
|app/|Contains the controllers, models, views, helpers, mailers and assets for your application. You'll focus on this folder for the remainder of this guide.|
|
164
|
-
|bin/|Contains the rails script that starts your app and can contain other scripts you use to setup, deploy or run your application.|
|
165
|
-
|config/|Configure your application's routes, database, and more. This is covered in more detail in [Configuring Rails Applications](configuring.html).|
|
166
|
-
|config.ru|Rack configuration for Rack based servers used to start the application.|
|
167
|
-
|db/|Contains your current database schema, as well as the database migrations.|
|
168
|
-
|Gemfile<br>Gemfile.lock|These files allow you to specify what gem dependencies are needed for your Rails application. These files are used by the Bundler gem. For more information about Bundler, see the [Bundler website](http://bundler.io).|
|
169
|
-
|lib/|Extended modules for your application.|
|
170
|
-
|log/|Application log files.|
|
171
|
-
|public/|The only folder seen by the world as-is. Contains static files and compiled assets.|
|
172
|
-
|Rakefile|This file locates and loads tasks that can be run from the command line. The task definitions are defined throughout the components of Rails. Rather than changing Rakefile, you should add your own tasks by adding files to the lib/tasks directory of your application.|
|
173
|
-
|README.rdoc|This is a brief instruction manual for your application. You should edit this file to tell others what your application does, how to set it up, and so on.|
|
174
|
-
|test/|Unit tests, fixtures, and other test apparatus. These are covered in [Testing Rails Applications](testing.html).|
|
175
|
-
|tmp/|Temporary files (like cache, pid, and session files).|
|
176
|
-
|vendor/|A place for all third-party code. In a typical Rails application this includes vendored gems.|
|
177
|
-
|
178
|
-
Hello, Rails!
|
179
|
-
-------------
|
180
|
-
|
181
|
-
To begin with, let's get some text up on screen quickly. To do this, you need to
|
182
|
-
get your Rails application server running.
|
183
|
-
|
184
|
-
### Starting up the Web Server
|
185
|
-
|
186
|
-
You actually have a functional Rails application already. To see it, you need to
|
187
|
-
start a web server on your development machine. You can do this by running the
|
188
|
-
following in the `blog` directory:
|
189
|
-
|
190
|
-
```bash
|
191
|
-
$ bin/rails server
|
192
|
-
```
|
193
|
-
|
194
|
-
TIP: 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).
|
206
|
-
|
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:
|
210
|
-
|
211
|
-
![Welcome aboard screenshot](images/getting_started/rails_welcome.png)
|
212
|
-
|
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.
|
219
|
-
|
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.
|
224
|
-
|
225
|
-
### Say "Hello", Rails
|
226
|
-
|
227
|
-
To get Rails saying "Hello", you need to create at minimum a _controller_ and a
|
228
|
-
_view_.
|
229
|
-
|
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.
|
235
|
-
|
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.
|
242
|
-
|
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:
|
246
|
-
|
247
|
-
```bash
|
248
|
-
$ bin/rails generate controller welcome index
|
249
|
-
```
|
250
|
-
|
251
|
-
Rails will create several files and a route for you.
|
252
|
-
|
253
|
-
```bash
|
254
|
-
create app/controllers/welcome_controller.rb
|
255
|
-
route get 'welcome/index'
|
256
|
-
invoke erb
|
257
|
-
create app/views/welcome
|
258
|
-
create app/views/welcome/index.html.erb
|
259
|
-
invoke test_unit
|
260
|
-
create test/controllers/welcome_controller_test.rb
|
261
|
-
invoke helper
|
262
|
-
create app/helpers/welcome_helper.rb
|
263
|
-
invoke assets
|
264
|
-
invoke coffee
|
265
|
-
create app/assets/javascripts/welcome.js.coffee
|
266
|
-
invoke scss
|
267
|
-
create app/assets/stylesheets/welcome.css.scss
|
268
|
-
```
|
269
|
-
|
270
|
-
Most important of these are of course the controller, located at
|
271
|
-
`app/controllers/welcome_controller.rb` and the view, located at
|
272
|
-
`app/views/welcome/index.html.erb`.
|
273
|
-
|
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:
|
277
|
-
|
278
|
-
```html
|
279
|
-
<h1>Hello, Rails!</h1>
|
280
|
-
```
|
281
|
-
|
282
|
-
### Setting the Application Home Page
|
283
|
-
|
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.
|
288
|
-
|
289
|
-
Next, you have to tell Rails where your actual home page is located.
|
290
|
-
|
291
|
-
Open the file `config/routes.rb` in your editor.
|
292
|
-
|
293
|
-
```ruby
|
294
|
-
Rails.application.routes.draw do
|
295
|
-
get 'welcome/index'
|
296
|
-
|
297
|
-
# The priority is based upon order of creation:
|
298
|
-
# first created -> highest priority.
|
299
|
-
#
|
300
|
-
# You can have the root of your site routed with "root"
|
301
|
-
# root 'welcome#index'
|
302
|
-
#
|
303
|
-
# ...
|
304
|
-
```
|
305
|
-
|
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:
|
312
|
-
|
313
|
-
```ruby
|
314
|
-
root 'welcome#index'
|
315
|
-
```
|
316
|
-
|
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`).
|
322
|
-
|
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.
|
328
|
-
|
329
|
-
TIP: For more information about routing, refer to [Rails Routing from the Outside In](routing.html).
|
330
|
-
|
331
|
-
Getting Up and Running
|
332
|
-
----------------------
|
333
|
-
|
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.
|
336
|
-
|
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.
|
342
|
-
|
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:
|
346
|
-
|
347
|
-
```ruby
|
348
|
-
Rails.application.routes.draw do
|
349
|
-
|
350
|
-
resources :articles
|
351
|
-
|
352
|
-
root 'welcome#index'
|
353
|
-
end
|
354
|
-
```
|
355
|
-
|
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.
|
360
|
-
|
361
|
-
```bash
|
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
|
373
|
-
```
|
374
|
-
|
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:
|
378
|
-
|
379
|
-
![The new article form](images/getting_started/new_article.png)
|
380
|
-
|
381
|
-
It will look a little basic for now, but that's ok. We'll look at improving the
|
382
|
-
styling for it afterwards.
|
383
|
-
|
384
|
-
### Laying down the ground work
|
385
|
-
|
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:
|
391
|
-
|
392
|
-
![Another routing error, uninitialized constant ArticlesController](images/getting_started/routing_error_no_controller.png)
|
393
|
-
|
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:
|
398
|
-
|
399
|
-
```bash
|
400
|
-
$ bin/rails generate controller articles
|
401
|
-
```
|
402
|
-
|
403
|
-
If you open up the newly generated `app/controllers/articles_controller.rb`
|
404
|
-
you'll see a fairly empty controller:
|
405
|
-
|
406
|
-
```ruby
|
407
|
-
class ArticlesController < ApplicationController
|
408
|
-
end
|
409
|
-
```
|
410
|
-
|
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/).
|
420
|
-
|
421
|
-
If you refresh <http://localhost:3000/articles/new> now, you'll get a new error:
|
422
|
-
|
423
|
-
![Unknown action new for ArticlesController!](images/getting_started/unknown_action_new_for_articles.png)
|
424
|
-
|
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.
|
429
|
-
|
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:
|
434
|
-
|
435
|
-
```ruby
|
436
|
-
class ArticlesController < ApplicationController
|
437
|
-
def new
|
438
|
-
end
|
439
|
-
end
|
440
|
-
```
|
441
|
-
|
442
|
-
With the `new` method defined in `ArticlesController`, if you refresh
|
443
|
-
<http://localhost:3000/articles/new> you'll see another error:
|
444
|
-
|
445
|
-
![Template is missing for articles/new]
|
446
|
-
(images/getting_started/template_is_missing_articles_new.png)
|
447
|
-
|
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.
|
451
|
-
|
452
|
-
In the above image, the bottom line has been truncated. Let's see what the full
|
453
|
-
thing looks like:
|
454
|
-
|
455
|
-
>Missing template articles/new, application/new with {locale:[:en], formats:[:html], handlers:[:erb, :builder, :coffee]}. Searched in: * "/path/to/blog/app/views"
|
456
|
-
|
457
|
-
That's quite a lot of text! Let's quickly go through and understand what each
|
458
|
-
part of it does.
|
459
|
-
|
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`.
|
464
|
-
|
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.
|
473
|
-
|
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.
|
477
|
-
|
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.
|
487
|
-
|
488
|
-
Go ahead now and create a new file at `app/views/articles/new.html.erb` and
|
489
|
-
write this content in it:
|
490
|
-
|
491
|
-
```html
|
492
|
-
<h1>New Article</h1>
|
493
|
-
```
|
494
|
-
|
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.
|
498
|
-
|
499
|
-
### The first form
|
500
|
-
|
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`:
|
505
|
-
|
506
|
-
```html+erb
|
507
|
-
<%= form_for :article do |f| %>
|
508
|
-
<p>
|
509
|
-
<%= f.label :title %><br>
|
510
|
-
<%= f.text_field :title %>
|
511
|
-
</p>
|
512
|
-
|
513
|
-
<p>
|
514
|
-
<%= f.label :text %><br>
|
515
|
-
<%= f.text_area :text %>
|
516
|
-
</p>
|
517
|
-
|
518
|
-
<p>
|
519
|
-
<%= f.submit %>
|
520
|
-
</p>
|
521
|
-
<% end %>
|
522
|
-
```
|
523
|
-
|
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!
|
526
|
-
|
527
|
-
When you call `form_for`, you pass it an identifying object for this
|
528
|
-
form. In this case, it's the symbol `:article`. This tells the `form_for`
|
529
|
-
helper what this form is for. Inside the block for this method, the
|
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.
|
533
|
-
|
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.
|
539
|
-
|
540
|
-
The form needs to use a different URL in order to go somewhere else.
|
541
|
-
This can be done quite simply with the `:url` option of `form_for`.
|
542
|
-
Typically in Rails, the action that is used for new form submissions
|
543
|
-
like this is called "create", and so the form should be pointed to that action.
|
544
|
-
|
545
|
-
Edit the `form_for` line inside `app/views/articles/new.html.erb` to look like
|
546
|
-
this:
|
547
|
-
|
548
|
-
```html+erb
|
549
|
-
<%= form_for :article, url: articles_path do |f| %>
|
550
|
-
```
|
551
|
-
|
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`:
|
555
|
-
|
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
|
-
```
|
569
|
-
|
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`.
|
574
|
-
|
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:
|
579
|
-
|
580
|
-
![Unknown action create for ArticlesController]
|
581
|
-
(images/getting_started/unknown_action_create_for_articles.png)
|
582
|
-
|
583
|
-
You now need to create the `create` action within the `ArticlesController` for
|
584
|
-
this to work.
|
585
|
-
|
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:
|
591
|
-
|
592
|
-
```ruby
|
593
|
-
class ArticlesController < ApplicationController
|
594
|
-
def new
|
595
|
-
end
|
596
|
-
|
597
|
-
def create
|
598
|
-
end
|
599
|
-
end
|
600
|
-
```
|
601
|
-
|
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.
|
605
|
-
|
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:
|
610
|
-
|
611
|
-
```ruby
|
612
|
-
def create
|
613
|
-
render plain: params[:article].inspect
|
614
|
-
end
|
615
|
-
```
|
616
|
-
|
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".
|
625
|
-
|
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:
|
628
|
-
|
629
|
-
```ruby
|
630
|
-
{"title"=>"First article!", "text"=>"This is my first article."}
|
631
|
-
```
|
632
|
-
|
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.
|
636
|
-
|
637
|
-
### Creating the Article model
|
638
|
-
|
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:
|
643
|
-
|
644
|
-
```bash
|
645
|
-
$ bin/rails generate model Article title:string text:text
|
646
|
-
```
|
647
|
-
|
648
|
-
With that command we told Rails that we want a `Article` model, together
|
649
|
-
with a _title_ attribute of type string, and a _text_ attribute
|
650
|
-
of type text. Those attributes are automatically added to the `articles`
|
651
|
-
table in the database and mapped to the `Article` model.
|
652
|
-
|
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.
|
657
|
-
|
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.
|
661
|
-
|
662
|
-
### Running a Migration
|
663
|
-
|
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.
|
670
|
-
|
671
|
-
If you look in the `db/migrate/20140120191729_create_articles.rb` file (remember,
|
672
|
-
yours will have a slightly different name), here's what you'll find:
|
673
|
-
|
674
|
-
```ruby
|
675
|
-
class CreateArticles < ActiveRecord::Migration
|
676
|
-
def change
|
677
|
-
create_table :articles do |t|
|
678
|
-
t.string :title
|
679
|
-
t.text :text
|
680
|
-
|
681
|
-
t.timestamps null: false
|
682
|
-
end
|
683
|
-
end
|
684
|
-
end
|
685
|
-
```
|
686
|
-
|
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.
|
693
|
-
|
694
|
-
TIP: For more information about migrations, refer to [Rails Database Migrations]
|
695
|
-
(migrations.html).
|
696
|
-
|
697
|
-
At this point, you can use a rake command to run the migration:
|
698
|
-
|
699
|
-
```bash
|
700
|
-
$ bin/rake db:migrate
|
701
|
-
```
|
702
|
-
|
703
|
-
Rails will execute this migration command and tell you it created the Articles
|
704
|
-
table.
|
705
|
-
|
706
|
-
```bash
|
707
|
-
== CreateArticles: migrating ==================================================
|
708
|
-
-- create_table(:articles)
|
709
|
-
-> 0.0019s
|
710
|
-
== CreateArticles: migrated (0.0020s) =========================================
|
711
|
-
```
|
712
|
-
|
713
|
-
NOTE. Because you're working in the development environment by default, this
|
714
|
-
command will apply to the database defined in the `development` section of your
|
715
|
-
`config/database.yml` file. If you would like to execute migrations in another
|
716
|
-
environment, for instance in production, you must explicitly pass it when
|
717
|
-
invoking the command: `bin/rake db:migrate RAILS_ENV=production`.
|
718
|
-
|
719
|
-
### Saving data in the controller
|
720
|
-
|
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:
|
725
|
-
|
726
|
-
```ruby
|
727
|
-
def create
|
728
|
-
@article = Article.new(params[:article])
|
729
|
-
|
730
|
-
@article.save
|
731
|
-
redirect_to @article
|
732
|
-
end
|
733
|
-
```
|
734
|
-
|
735
|
-
Here's what's going on: every Rails model can be initialized with its
|
736
|
-
respective attributes, which are automatically mapped to the respective
|
737
|
-
database columns. In the first line we do just that (remember that
|
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.
|
741
|
-
|
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.
|
743
|
-
|
744
|
-
TIP: As we'll see later, `@article.save` returns a boolean indicating whether
|
745
|
-
the article was saved or not.
|
746
|
-
|
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
|
-
```
|
774
|
-
|
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:
|
779
|
-
|
780
|
-
```ruby
|
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
|
809
|
-
```
|
810
|
-
|
811
|
-
The special syntax `:id` tells rails that this route expects an `:id`
|
812
|
-
parameter, which in our case will be the id of the article.
|
813
|
-
|
814
|
-
As we did before, we need to add the `show` action in
|
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:
|
824
|
-
|
825
|
-
```ruby
|
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
|
835
|
-
```
|
836
|
-
|
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
|
841
|
-
variables to the view.
|
842
|
-
|
843
|
-
Now, create a new file `app/views/articles/show.html.erb` with the following
|
844
|
-
content:
|
845
|
-
|
846
|
-
```html+erb
|
847
|
-
<p>
|
848
|
-
<strong>Title:</strong>
|
849
|
-
<%= @article.title %>
|
850
|
-
</p>
|
851
|
-
|
852
|
-
<p>
|
853
|
-
<strong>Text:</strong>
|
854
|
-
<%= @article.text %>
|
855
|
-
</p>
|
856
|
-
```
|
857
|
-
|
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!
|
860
|
-
|
861
|
-
![Show action for articles](images/getting_started/show_action_for_articles.png)
|
862
|
-
|
863
|
-
### Listing all articles
|
864
|
-
|
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:
|
867
|
-
|
868
|
-
```
|
869
|
-
articles GET /articles(.:format) articles#index
|
870
|
-
```
|
871
|
-
|
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:
|
876
|
-
|
877
|
-
```ruby
|
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
|
886
|
-
|
887
|
-
def new
|
888
|
-
end
|
889
|
-
|
890
|
-
# snippet for brevity
|
891
|
-
```
|
892
|
-
|
893
|
-
And then finally, add the view for this action, located at
|
894
|
-
`app/views/articles/index.html.erb`:
|
895
|
-
|
896
|
-
```html+erb
|
897
|
-
<h1>Listing articles</h1>
|
898
|
-
|
899
|
-
<table>
|
900
|
-
<tr>
|
901
|
-
<th>Title</th>
|
902
|
-
<th>Text</th>
|
903
|
-
</tr>
|
904
|
-
|
905
|
-
<% @articles.each do |article| %>
|
906
|
-
<tr>
|
907
|
-
<td><%= article.title %></td>
|
908
|
-
<td><%= article.text %></td>
|
909
|
-
</tr>
|
910
|
-
<% end %>
|
911
|
-
</table>
|
912
|
-
```
|
913
|
-
|
914
|
-
Now if you go to <http://localhost:3000/articles> you will see a list of all the
|
915
|
-
articles that you have created.
|
916
|
-
|
917
|
-
### Adding links
|
918
|
-
|
919
|
-
You can now create, show, and list articles. Now let's add some links to
|
920
|
-
navigate through pages.
|
921
|
-
|
922
|
-
Open `app/views/welcome/index.html.erb` and modify it as follows:
|
923
|
-
|
924
|
-
```html+erb
|
925
|
-
<h1>Hello, Rails!</h1>
|
926
|
-
<%= link_to 'My Blog', controller: 'articles' %>
|
927
|
-
```
|
928
|
-
|
929
|
-
The `link_to` method is one of Rails' built-in view helpers. It creates a
|
930
|
-
hyperlink based on text to display and where to go - in this case, to the path
|
931
|
-
for articles.
|
932
|
-
|
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:
|
936
|
-
|
937
|
-
```erb
|
938
|
-
<%= link_to 'New article', new_article_path %>
|
939
|
-
```
|
940
|
-
|
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:
|
945
|
-
|
946
|
-
```erb
|
947
|
-
<%= form_for :article, url: articles_path do |f| %>
|
948
|
-
...
|
949
|
-
<% end %>
|
950
|
-
|
951
|
-
<%= link_to 'Back', articles_path %>
|
952
|
-
```
|
953
|
-
|
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:
|
957
|
-
|
958
|
-
```html+erb
|
959
|
-
<p>
|
960
|
-
<strong>Title:</strong>
|
961
|
-
<%= @article.title %>
|
962
|
-
</p>
|
963
|
-
|
964
|
-
<p>
|
965
|
-
<strong>Text:</strong>
|
966
|
-
<%= @article.text %>
|
967
|
-
</p>
|
968
|
-
|
969
|
-
<%= link_to 'Back', articles_path %>
|
970
|
-
```
|
971
|
-
|
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.
|
975
|
-
|
976
|
-
TIP: In development mode (which is what you're working in by default), Rails
|
977
|
-
reloads your application with every browser request, so there's no need to stop
|
978
|
-
and restart the web server when a change is made.
|
979
|
-
|
980
|
-
### Adding Some Validation
|
981
|
-
|
982
|
-
The model file, `app/models/article.rb` is about as simple as it can get:
|
983
|
-
|
984
|
-
```ruby
|
985
|
-
class Article < ActiveRecord::Base
|
986
|
-
end
|
987
|
-
```
|
988
|
-
|
989
|
-
There isn't much to this file - but note that the `Article` class inherits from
|
990
|
-
`ActiveRecord::Base`. Active Record supplies a great deal of functionality to
|
991
|
-
your Rails models for free, including basic database CRUD (Create, Read, Update,
|
992
|
-
Destroy) operations, data validation, as well as sophisticated search support
|
993
|
-
and the ability to relate multiple models to one another.
|
994
|
-
|
995
|
-
Rails includes methods to help you validate the data that you send to models.
|
996
|
-
Open the `app/models/article.rb` file and edit it:
|
997
|
-
|
998
|
-
```ruby
|
999
|
-
class Article < ActiveRecord::Base
|
1000
|
-
validates :title, presence: true,
|
1001
|
-
length: { minimum: 5 }
|
1002
|
-
end
|
1003
|
-
```
|
1004
|
-
|
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,
|
1007
|
-
including the presence or uniqueness of columns, their format, and the
|
1008
|
-
existence of associated objects. Validations are covered in detail in [Active
|
1009
|
-
Record Validations](active_record_validations.html).
|
1010
|
-
|
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:
|
1018
|
-
|
1019
|
-
```ruby
|
1020
|
-
def new
|
1021
|
-
@article = Article.new
|
1022
|
-
end
|
1023
|
-
|
1024
|
-
def create
|
1025
|
-
@article = Article.new(article_params)
|
1026
|
-
|
1027
|
-
if @article.save
|
1028
|
-
redirect_to @article
|
1029
|
-
else
|
1030
|
-
render 'new'
|
1031
|
-
end
|
1032
|
-
end
|
1033
|
-
|
1034
|
-
private
|
1035
|
-
def article_params
|
1036
|
-
params.require(:article).permit(:title, :text)
|
1037
|
-
end
|
1038
|
-
```
|
1039
|
-
|
1040
|
-
The `new` action is now creating a new instance variable called `@article`, and
|
1041
|
-
you'll see why that is in just a few moments.
|
1042
|
-
|
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.
|
1048
|
-
|
1049
|
-
If you reload
|
1050
|
-
<http://localhost:3000/articles/new> and
|
1051
|
-
try to save an article without a title, Rails will send you back to the
|
1052
|
-
form, but that's not very useful. You need to tell the user that
|
1053
|
-
something went wrong. To do that, you'll modify
|
1054
|
-
`app/views/articles/new.html.erb` to check for error messages:
|
1055
|
-
|
1056
|
-
```html+erb
|
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>
|
1071
|
-
<% end %>
|
1072
|
-
|
1073
|
-
<p>
|
1074
|
-
<%= f.label :title %><br>
|
1075
|
-
<%= f.text_field :title %>
|
1076
|
-
</p>
|
1077
|
-
|
1078
|
-
<p>
|
1079
|
-
<%= f.label :text %><br>
|
1080
|
-
<%= f.text_area :text %>
|
1081
|
-
</p>
|
1082
|
-
|
1083
|
-
<p>
|
1084
|
-
<%= f.submit %>
|
1085
|
-
</p>
|
1086
|
-
|
1087
|
-
<% end %>
|
1088
|
-
|
1089
|
-
<%= link_to 'Back', articles_path %>
|
1090
|
-
```
|
1091
|
-
|
1092
|
-
A few things are going on. We check if there are any errors with
|
1093
|
-
`@article.errors.any?`, and in that case we show a list of all
|
1094
|
-
errors with `@article.errors.full_messages`.
|
1095
|
-
|
1096
|
-
`pluralize` is a rails helper that takes a number and a string as its
|
1097
|
-
arguments. If the number is greater than one, the string will be automatically
|
1098
|
-
pluralized.
|
1099
|
-
|
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.
|
1103
|
-
|
1104
|
-
TIP: Rails automatically wraps fields that contain an error with a div
|
1105
|
-
with class `field_with_errors`. You can define a css rule to make them
|
1106
|
-
standout.
|
1107
|
-
|
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>:
|
1111
|
-
|
1112
|
-
![Form With Errors](images/getting_started/form_with_errors.png)
|
1113
|
-
|
1114
|
-
### Updating Articles
|
1115
|
-
|
1116
|
-
We've covered the "CR" part of CRUD. Now let's focus on the "U" part, updating
|
1117
|
-
articles.
|
1118
|
-
|
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:
|
1121
|
-
|
1122
|
-
```ruby
|
1123
|
-
def new
|
1124
|
-
@article = Article.new
|
1125
|
-
end
|
1126
|
-
|
1127
|
-
def edit
|
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
|
1139
|
-
end
|
1140
|
-
```
|
1141
|
-
|
1142
|
-
The view will contain a form similar to the one we used when creating
|
1143
|
-
new articles. Create a file called `app/views/articles/edit.html.erb` and make
|
1144
|
-
it look as follows:
|
1145
|
-
|
1146
|
-
```html+erb
|
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>
|
1163
|
-
<% end %>
|
1164
|
-
|
1165
|
-
<p>
|
1166
|
-
<%= f.label :title %><br>
|
1167
|
-
<%= f.text_field :title %>
|
1168
|
-
</p>
|
1169
|
-
|
1170
|
-
<p>
|
1171
|
-
<%= f.label :text %><br>
|
1172
|
-
<%= f.text_area :text %>
|
1173
|
-
</p>
|
1174
|
-
|
1175
|
-
<p>
|
1176
|
-
<%= f.submit %>
|
1177
|
-
</p>
|
1178
|
-
|
1179
|
-
<% end %>
|
1180
|
-
|
1181
|
-
<%= link_to 'Back', articles_path %>
|
1182
|
-
```
|
1183
|
-
|
1184
|
-
This time we point the form to the `update` action, which is not defined yet
|
1185
|
-
but will be very soon.
|
1186
|
-
|
1187
|
-
The `method: :patch` option tells Rails that we want this form to be submitted
|
1188
|
-
via the `PATCH` HTTP method which is the HTTP method you're expected to use to
|
1189
|
-
**update** resources according to the REST protocol.
|
1190
|
-
|
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).
|
1197
|
-
|
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:
|
1201
|
-
|
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
|
-
|
1213
|
-
def update
|
1214
|
-
@article = Article.find(params[:id])
|
1215
|
-
|
1216
|
-
if @article.update(article_params)
|
1217
|
-
redirect_to @article
|
1218
|
-
else
|
1219
|
-
render 'edit'
|
1220
|
-
end
|
1221
|
-
end
|
1222
|
-
|
1223
|
-
private
|
1224
|
-
def article_params
|
1225
|
-
params.require(:article).permit(:title, :text)
|
1226
|
-
end
|
1227
|
-
```
|
1228
|
-
|
1229
|
-
The new method, `update`, is used when you want to update a record
|
1230
|
-
that already exists, and it accepts a hash containing the attributes
|
1231
|
-
that you want to update. As before, if there was an error updating the
|
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.
|
1236
|
-
|
1237
|
-
TIP: You don't need to pass all attributes to `update`. For
|
1238
|
-
example, if you'd call `@article.update(title: 'A new title')`
|
1239
|
-
Rails would only update the `title` attribute, leaving all other
|
1240
|
-
attributes untouched.
|
1241
|
-
|
1242
|
-
Finally, we want to show a link to the `edit` action in the list of all the
|
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:
|
1245
|
-
|
1246
|
-
```html+erb
|
1247
|
-
<table>
|
1248
|
-
<tr>
|
1249
|
-
<th>Title</th>
|
1250
|
-
<th>Text</th>
|
1251
|
-
<th colspan="2"></th>
|
1252
|
-
</tr>
|
1253
|
-
|
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 %>
|
1262
|
-
</table>
|
1263
|
-
```
|
1264
|
-
|
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:
|
1268
|
-
|
1269
|
-
```html+erb
|
1270
|
-
...
|
1271
|
-
|
1272
|
-
<%= link_to 'Edit', edit_article_path(@article) %> |
|
1273
|
-
<%= link_to 'Back', articles_path %>
|
1274
|
-
```
|
1275
|
-
|
1276
|
-
And here's how our app looks so far:
|
1277
|
-
|
1278
|
-
![Index action with edit link](images/getting_started/index_action_with_edit_link.png)
|
1279
|
-
|
1280
|
-
### Using partials to clean up duplication in views
|
1281
|
-
|
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.
|
1286
|
-
|
1287
|
-
TIP: You can read more about partials in the
|
1288
|
-
[Layouts and Rendering in Rails](layouts_and_rendering.html) guide.
|
1289
|
-
|
1290
|
-
Create a new file `app/views/articles/_form.html.erb` with the following
|
1291
|
-
content:
|
1292
|
-
|
1293
|
-
```html+erb
|
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>
|
1308
|
-
<% end %>
|
1309
|
-
|
1310
|
-
<p>
|
1311
|
-
<%= f.label :title %><br>
|
1312
|
-
<%= f.text_field :title %>
|
1313
|
-
</p>
|
1314
|
-
|
1315
|
-
<p>
|
1316
|
-
<%= f.label :text %><br>
|
1317
|
-
<%= f.text_area :text %>
|
1318
|
-
</p>
|
1319
|
-
|
1320
|
-
<p>
|
1321
|
-
<%= f.submit %>
|
1322
|
-
</p>
|
1323
|
-
|
1324
|
-
<% end %>
|
1325
|
-
```
|
1326
|
-
|
1327
|
-
Everything except for the `form_for` declaration remained the same.
|
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:
|
1337
|
-
|
1338
|
-
```html+erb
|
1339
|
-
<h1>New article</h1>
|
1340
|
-
|
1341
|
-
<%= render 'form' %>
|
1342
|
-
|
1343
|
-
<%= link_to 'Back', articles_path %>
|
1344
|
-
```
|
1345
|
-
|
1346
|
-
Then do the same for the `app/views/articles/edit.html.erb` view:
|
1347
|
-
|
1348
|
-
```html+erb
|
1349
|
-
<h1>Edit article</h1>
|
1350
|
-
|
1351
|
-
<%= render 'form' %>
|
1352
|
-
|
1353
|
-
<%= link_to 'Back', articles_path %>
|
1354
|
-
```
|
1355
|
-
|
1356
|
-
### Deleting Articles
|
1357
|
-
|
1358
|
-
We're now ready to cover the "D" part of CRUD, deleting articles from the
|
1359
|
-
database. Following the REST convention, the route for
|
1360
|
-
deleting articles as per output of `bin/rake routes` is:
|
1361
|
-
|
1362
|
-
```ruby
|
1363
|
-
DELETE /articles/:id(.:format) articles#destroy
|
1364
|
-
```
|
1365
|
-
|
1366
|
-
The `delete` routing method should be used for routes that destroy
|
1367
|
-
resources. If this was left as a typical `get` route, it could be possible for
|
1368
|
-
people to craft malicious URLs like this:
|
1369
|
-
|
1370
|
-
```html
|
1371
|
-
<a href='http://example.com/articles/1/destroy'>look at this cat!</a>
|
1372
|
-
```
|
1373
|
-
|
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:
|
1379
|
-
|
1380
|
-
```ruby
|
1381
|
-
def destroy
|
1382
|
-
@article = Article.find(params[:id])
|
1383
|
-
@article.destroy
|
1384
|
-
|
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
|
1441
|
-
end
|
1442
|
-
```
|
1443
|
-
|
1444
|
-
You can call `destroy` on Active Record objects when you want to delete
|
1445
|
-
them from the database. Note that we don't need to add a view for this
|
1446
|
-
action since we're redirecting to the `index` action.
|
1447
|
-
|
1448
|
-
Finally, add a 'Destroy' link to your `index` action template
|
1449
|
-
(`app/views/articles/index.html.erb`) to wrap everything together.
|
1450
|
-
|
1451
|
-
```html+erb
|
1452
|
-
<h1>Listing Articles</h1>
|
1453
|
-
<%= link_to 'New article', new_article_path %>
|
1454
|
-
<table>
|
1455
|
-
<tr>
|
1456
|
-
<th>Title</th>
|
1457
|
-
<th>Text</th>
|
1458
|
-
<th colspan="3"></th>
|
1459
|
-
</tr>
|
1460
|
-
|
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 %>
|
1472
|
-
</table>
|
1473
|
-
```
|
1474
|
-
|
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.
|
1483
|
-
|
1484
|
-
![Confirm Dialog](images/getting_started/confirm_dialog.png)
|
1485
|
-
|
1486
|
-
Congratulations, you can now create, show, list, update and destroy
|
1487
|
-
articles.
|
1488
|
-
|
1489
|
-
TIP: In general, Rails encourages using resources objects instead of
|
1490
|
-
declaring routes manually. For more information about routing, see
|
1491
|
-
[Rails Routing from the Outside In](routing.html).
|
1492
|
-
|
1493
|
-
Adding a Second Model
|
1494
|
-
---------------------
|
1495
|
-
|
1496
|
-
It's time to add a second model to the application. The second model will handle
|
1497
|
-
comments on articles.
|
1498
|
-
|
1499
|
-
### Generating a Model
|
1500
|
-
|
1501
|
-
We're going to see the same generator that we used before when creating
|
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:
|
1504
|
-
|
1505
|
-
```bash
|
1506
|
-
$ bin/rails generate model Comment commenter:string body:text article:references
|
1507
|
-
```
|
1508
|
-
|
1509
|
-
This command will generate four files:
|
1510
|
-
|
1511
|
-
| File | Purpose |
|
1512
|
-
| -------------------------------------------- | ------------------------------------------------------------------------------------------------------ |
|
1513
|
-
| db/migrate/20140120201010_create_comments.rb | Migration to create the comments table in your database (your name will include a different timestamp) |
|
1514
|
-
| app/models/comment.rb | The Comment model |
|
1515
|
-
| test/models/comment_test.rb | Testing harness for the comments model |
|
1516
|
-
| test/fixtures/comments.yml | Sample comments for use in testing |
|
1517
|
-
|
1518
|
-
First, take a look at `app/models/comment.rb`:
|
1519
|
-
|
1520
|
-
```ruby
|
1521
|
-
class Comment < ActiveRecord::Base
|
1522
|
-
belongs_to :article
|
1523
|
-
end
|
1524
|
-
```
|
1525
|
-
|
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_.
|
1528
|
-
You'll learn a little about associations in the next section of this guide.
|
1529
|
-
|
1530
|
-
In addition to the model, Rails has also made a migration to create the
|
1531
|
-
corresponding database table:
|
1532
|
-
|
1533
|
-
```ruby
|
1534
|
-
class CreateComments < ActiveRecord::Migration
|
1535
|
-
def change
|
1536
|
-
create_table :comments do |t|
|
1537
|
-
t.string :commenter
|
1538
|
-
t.text :body
|
1539
|
-
t.references :article, index: true, foreign_key: true
|
1540
|
-
|
1541
|
-
t.timestamps null: false
|
1542
|
-
end
|
1543
|
-
end
|
1544
|
-
end
|
1545
|
-
```
|
1546
|
-
|
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:
|
1550
|
-
|
1551
|
-
```bash
|
1552
|
-
$ bin/rake db:migrate
|
1553
|
-
```
|
1554
|
-
|
1555
|
-
Rails is smart enough to only execute the migrations that have not already been
|
1556
|
-
run against the current database, so in this case you will just see:
|
1557
|
-
|
1558
|
-
```bash
|
1559
|
-
== CreateComments: migrating =================================================
|
1560
|
-
-- create_table(:comments)
|
1561
|
-
-> 0.0115s
|
1562
|
-
== CreateComments: migrated (0.0119s) ========================================
|
1563
|
-
```
|
1564
|
-
|
1565
|
-
### Associating Models
|
1566
|
-
|
1567
|
-
Active Record associations let you easily declare the relationship between two
|
1568
|
-
models. In the case of comments and articles, you could write out the
|
1569
|
-
relationships this way:
|
1570
|
-
|
1571
|
-
* Each comment belongs to one article.
|
1572
|
-
* One article can have many comments.
|
1573
|
-
|
1574
|
-
In fact, this is very close to the syntax that Rails uses to declare this
|
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:
|
1577
|
-
|
1578
|
-
```ruby
|
1579
|
-
class Comment < ActiveRecord::Base
|
1580
|
-
belongs_to :article
|
1581
|
-
end
|
1582
|
-
```
|
1583
|
-
|
1584
|
-
You'll need to edit `app/models/article.rb` to add the other side of the
|
1585
|
-
association:
|
1586
|
-
|
1587
|
-
```ruby
|
1588
|
-
class Article < ActiveRecord::Base
|
1589
|
-
has_many :comments
|
1590
|
-
validates :title, presence: true,
|
1591
|
-
length: { minimum: 5 }
|
1592
|
-
end
|
1593
|
-
```
|
1594
|
-
|
1595
|
-
These two declarations enable a good bit of automatic behavior. For example, if
|
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`.
|
1599
|
-
|
1600
|
-
TIP: For more information on Active Record associations, see the [Active Record
|
1601
|
-
Associations](association_basics.html) guide.
|
1602
|
-
|
1603
|
-
### Adding a Route for Comments
|
1604
|
-
|
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
|
1607
|
-
`config/routes.rb` file again, and edit it as follows:
|
1608
|
-
|
1609
|
-
```ruby
|
1610
|
-
resources :articles do
|
1611
|
-
resources :comments
|
1612
|
-
end
|
1613
|
-
```
|
1614
|
-
|
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.
|
1618
|
-
|
1619
|
-
TIP: For more information on routing, see the [Rails Routing](routing.html)
|
1620
|
-
guide.
|
1621
|
-
|
1622
|
-
### Generating a Controller
|
1623
|
-
|
1624
|
-
With the model in hand, you can turn your attention to creating a matching
|
1625
|
-
controller. Again, we'll use the same generator we used before:
|
1626
|
-
|
1627
|
-
```bash
|
1628
|
-
$ bin/rails generate controller Comments
|
1629
|
-
```
|
1630
|
-
|
1631
|
-
This creates five files and one empty directory:
|
1632
|
-
|
1633
|
-
| File/Directory | Purpose |
|
1634
|
-
| -------------------------------------------- | ---------------------------------------- |
|
1635
|
-
| app/controllers/comments_controller.rb | The Comments controller |
|
1636
|
-
| app/views/comments/ | Views of the controller are stored here |
|
1637
|
-
| test/controllers/comments_controller_test.rb | The test for the controller |
|
1638
|
-
| app/helpers/comments_helper.rb | A view helper file |
|
1639
|
-
| app/assets/javascripts/comment.js.coffee | CoffeeScript for the controller |
|
1640
|
-
| app/assets/stylesheets/comment.css.scss | Cascading style sheet for the controller |
|
1641
|
-
|
1642
|
-
Like with any blog, our readers will create their comments directly after
|
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
|
1645
|
-
`CommentsController` is there to provide a method to create comments and delete
|
1646
|
-
spam comments when they arrive.
|
1647
|
-
|
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:
|
1650
|
-
|
1651
|
-
```html+erb
|
1652
|
-
<p>
|
1653
|
-
<strong>Title:</strong>
|
1654
|
-
<%= @article.title %>
|
1655
|
-
</p>
|
1656
|
-
|
1657
|
-
<p>
|
1658
|
-
<strong>Text:</strong>
|
1659
|
-
<%= @article.text %>
|
1660
|
-
</p>
|
1661
|
-
|
1662
|
-
<h2>Add a comment:</h2>
|
1663
|
-
<%= form_for([@article, @article.comments.build]) do |f| %>
|
1664
|
-
<p>
|
1665
|
-
<%= f.label :commenter %><br>
|
1666
|
-
<%= f.text_field :commenter %>
|
1667
|
-
</p>
|
1668
|
-
<p>
|
1669
|
-
<%= f.label :body %><br>
|
1670
|
-
<%= f.text_area :body %>
|
1671
|
-
</p>
|
1672
|
-
<p>
|
1673
|
-
<%= f.submit %>
|
1674
|
-
</p>
|
1675
|
-
<% end %>
|
1676
|
-
|
1677
|
-
<%= link_to 'Edit', edit_article_path(@article) %> |
|
1678
|
-
<%= link_to 'Back', articles_path %>
|
1679
|
-
```
|
1680
|
-
|
1681
|
-
This adds a form on the `Article` show page that creates a new comment by
|
1682
|
-
calling the `CommentsController` `create` action. The `form_for` call here uses
|
1683
|
-
an array, which will build a nested route, such as `/articles/1/comments`.
|
1684
|
-
|
1685
|
-
Let's wire up the `create` in `app/controllers/comments_controller.rb`:
|
1686
|
-
|
1687
|
-
```ruby
|
1688
|
-
class CommentsController < ApplicationController
|
1689
|
-
def create
|
1690
|
-
@article = Article.find(params[:article_id])
|
1691
|
-
@comment = @article.comments.create(comment_params)
|
1692
|
-
redirect_to article_path(@article)
|
1693
|
-
end
|
1694
|
-
|
1695
|
-
private
|
1696
|
-
def comment_params
|
1697
|
-
params.require(:comment).permit(:commenter, :body)
|
1698
|
-
end
|
1699
|
-
end
|
1700
|
-
```
|
1701
|
-
|
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.
|
1707
|
-
|
1708
|
-
In addition, the code takes advantage of some of the methods available for an
|
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.
|
1712
|
-
|
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`.
|
1718
|
-
|
1719
|
-
```html+erb
|
1720
|
-
<p>
|
1721
|
-
<strong>Title:</strong>
|
1722
|
-
<%= @article.title %>
|
1723
|
-
</p>
|
1724
|
-
|
1725
|
-
<p>
|
1726
|
-
<strong>Text:</strong>
|
1727
|
-
<%= @article.text %>
|
1728
|
-
</p>
|
1729
|
-
|
1730
|
-
<h2>Comments</h2>
|
1731
|
-
<% @article.comments.each do |comment| %>
|
1732
|
-
<p>
|
1733
|
-
<strong>Commenter:</strong>
|
1734
|
-
<%= comment.commenter %>
|
1735
|
-
</p>
|
1736
|
-
|
1737
|
-
<p>
|
1738
|
-
<strong>Comment:</strong>
|
1739
|
-
<%= comment.body %>
|
1740
|
-
</p>
|
1741
|
-
<% end %>
|
1742
|
-
|
1743
|
-
<h2>Add a comment:</h2>
|
1744
|
-
<%= form_for([@article, @article.comments.build]) do |f| %>
|
1745
|
-
<p>
|
1746
|
-
<%= f.label :commenter %><br>
|
1747
|
-
<%= f.text_field :commenter %>
|
1748
|
-
</p>
|
1749
|
-
<p>
|
1750
|
-
<%= f.label :body %><br>
|
1751
|
-
<%= f.text_area :body %>
|
1752
|
-
</p>
|
1753
|
-
<p>
|
1754
|
-
<%= f.submit %>
|
1755
|
-
</p>
|
1756
|
-
<% end %>
|
1757
|
-
|
1758
|
-
<%= link_to 'Edit', edit_article_path(@article) %> |
|
1759
|
-
<%= link_to 'Back', articles_path %>
|
1760
|
-
```
|
1761
|
-
|
1762
|
-
Now you can add articles and comments to your blog and have them show up in the
|
1763
|
-
right places.
|
1764
|
-
|
1765
|
-
![Article with Comments](images/getting_started/article_with_comments.png)
|
1766
|
-
|
1767
|
-
Refactoring
|
1768
|
-
-----------
|
1769
|
-
|
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.
|
1773
|
-
|
1774
|
-
### Rendering Partial Collections
|
1775
|
-
|
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
|
1778
|
-
following into it:
|
1779
|
-
|
1780
|
-
```html+erb
|
1781
|
-
<p>
|
1782
|
-
<strong>Commenter:</strong>
|
1783
|
-
<%= comment.commenter %>
|
1784
|
-
</p>
|
1785
|
-
|
1786
|
-
<p>
|
1787
|
-
<strong>Comment:</strong>
|
1788
|
-
<%= comment.body %>
|
1789
|
-
</p>
|
1790
|
-
```
|
1791
|
-
|
1792
|
-
Then you can change `app/views/articles/show.html.erb` to look like the
|
1793
|
-
following:
|
1794
|
-
|
1795
|
-
```html+erb
|
1796
|
-
<p>
|
1797
|
-
<strong>Title:</strong>
|
1798
|
-
<%= @article.title %>
|
1799
|
-
</p>
|
1800
|
-
|
1801
|
-
<p>
|
1802
|
-
<strong>Text:</strong>
|
1803
|
-
<%= @article.text %>
|
1804
|
-
</p>
|
1805
|
-
|
1806
|
-
<h2>Comments</h2>
|
1807
|
-
<%= render @article.comments %>
|
1808
|
-
|
1809
|
-
<h2>Add a comment:</h2>
|
1810
|
-
<%= form_for([@article, @article.comments.build]) do |f| %>
|
1811
|
-
<p>
|
1812
|
-
<%= f.label :commenter %><br>
|
1813
|
-
<%= f.text_field :commenter %>
|
1814
|
-
</p>
|
1815
|
-
<p>
|
1816
|
-
<%= f.label :body %><br>
|
1817
|
-
<%= f.text_area :body %>
|
1818
|
-
</p>
|
1819
|
-
<p>
|
1820
|
-
<%= f.submit %>
|
1821
|
-
</p>
|
1822
|
-
<% end %>
|
1823
|
-
|
1824
|
-
<%= link_to 'Edit', edit_article_path(@article) %> |
|
1825
|
-
<%= link_to 'Back', articles_path %>
|
1826
|
-
```
|
1827
|
-
|
1828
|
-
This will now render the partial in `app/views/comments/_comment.html.erb` once
|
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
|
1831
|
-
comment to a local variable named the same as the partial, in this case
|
1832
|
-
`comment` which is then available in the partial for us to show.
|
1833
|
-
|
1834
|
-
### Rendering a Partial Form
|
1835
|
-
|
1836
|
-
Let us also move that new comment section out to its own partial. Again, you
|
1837
|
-
create a file `app/views/comments/_form.html.erb` containing:
|
1838
|
-
|
1839
|
-
```html+erb
|
1840
|
-
<%= form_for([@article, @article.comments.build]) do |f| %>
|
1841
|
-
<p>
|
1842
|
-
<%= f.label :commenter %><br>
|
1843
|
-
<%= f.text_field :commenter %>
|
1844
|
-
</p>
|
1845
|
-
<p>
|
1846
|
-
<%= f.label :body %><br>
|
1847
|
-
<%= f.text_area :body %>
|
1848
|
-
</p>
|
1849
|
-
<p>
|
1850
|
-
<%= f.submit %>
|
1851
|
-
</p>
|
1852
|
-
<% end %>
|
1853
|
-
```
|
1854
|
-
|
1855
|
-
Then you make the `app/views/articles/show.html.erb` look like the following:
|
1856
|
-
|
1857
|
-
```html+erb
|
1858
|
-
<p>
|
1859
|
-
<strong>Title:</strong>
|
1860
|
-
<%= @article.title %>
|
1861
|
-
</p>
|
1862
|
-
|
1863
|
-
<p>
|
1864
|
-
<strong>Text:</strong>
|
1865
|
-
<%= @article.text %>
|
1866
|
-
</p>
|
1867
|
-
|
1868
|
-
<h2>Comments</h2>
|
1869
|
-
<%= render @article.comments %>
|
1870
|
-
|
1871
|
-
<h2>Add a comment:</h2>
|
1872
|
-
<%= render 'comments/form' %>
|
1873
|
-
|
1874
|
-
<%= link_to 'Edit', edit_article_path(@article) %> |
|
1875
|
-
<%= link_to 'Back', articles_path %>
|
1876
|
-
```
|
1877
|
-
|
1878
|
-
The second render just defines the partial template we want to render,
|
1879
|
-
`comments/form`. Rails is smart enough to spot the forward slash in that
|
1880
|
-
string and realize that you want to render the `_form.html.erb` file in
|
1881
|
-
the `app/views/comments` directory.
|
1882
|
-
|
1883
|
-
The `@article` object is available to any partials rendered in the view because
|
1884
|
-
we defined it as an instance variable.
|
1885
|
-
|
1886
|
-
Deleting Comments
|
1887
|
-
-----------------
|
1888
|
-
|
1889
|
-
Another important feature of a blog is being able to delete spam comments. To do
|
1890
|
-
this, we need to implement a link of some sort in the view and a `destroy`
|
1891
|
-
action in the `CommentsController`.
|
1892
|
-
|
1893
|
-
So first, let's add the delete link in the
|
1894
|
-
`app/views/comments/_comment.html.erb` partial:
|
1895
|
-
|
1896
|
-
```html+erb
|
1897
|
-
<p>
|
1898
|
-
<strong>Commenter:</strong>
|
1899
|
-
<%= comment.commenter %>
|
1900
|
-
</p>
|
1901
|
-
|
1902
|
-
<p>
|
1903
|
-
<strong>Comment:</strong>
|
1904
|
-
<%= comment.body %>
|
1905
|
-
</p>
|
1906
|
-
|
1907
|
-
<p>
|
1908
|
-
<%= link_to 'Destroy Comment', [comment.article, comment],
|
1909
|
-
method: :delete,
|
1910
|
-
data: { confirm: 'Are you sure?' } %>
|
1911
|
-
</p>
|
1912
|
-
```
|
1913
|
-
|
1914
|
-
Clicking this new "Destroy Comment" link will fire off a `DELETE
|
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`):
|
1918
|
-
|
1919
|
-
```ruby
|
1920
|
-
class CommentsController < ApplicationController
|
1921
|
-
def create
|
1922
|
-
@article = Article.find(params[:article_id])
|
1923
|
-
@comment = @article.comments.create(comment_params)
|
1924
|
-
redirect_to article_path(@article)
|
1925
|
-
end
|
1926
|
-
|
1927
|
-
def destroy
|
1928
|
-
@article = Article.find(params[:article_id])
|
1929
|
-
@comment = @article.comments.find(params[:id])
|
1930
|
-
@comment.destroy
|
1931
|
-
redirect_to article_path(@article)
|
1932
|
-
end
|
1933
|
-
|
1934
|
-
private
|
1935
|
-
def comment_params
|
1936
|
-
params.require(:comment).permit(:commenter, :body)
|
1937
|
-
end
|
1938
|
-
end
|
1939
|
-
```
|
1940
|
-
|
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.
|
1944
|
-
|
1945
|
-
|
1946
|
-
### Deleting Associated Objects
|
1947
|
-
|
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:
|
1952
|
-
|
1953
|
-
```ruby
|
1954
|
-
class Article < ActiveRecord::Base
|
1955
|
-
has_many :comments, dependent: :destroy
|
1956
|
-
validates :title, presence: true,
|
1957
|
-
length: { minimum: 5 }
|
1958
|
-
end
|
1959
|
-
```
|
1960
|
-
|
1961
|
-
Security
|
1962
|
-
--------
|
1963
|
-
|
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.
|
1968
|
-
|
1969
|
-
Rails provides a very simple HTTP authentication system that will work nicely in
|
1970
|
-
this situation.
|
1971
|
-
|
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
|
1975
|
-
action if that method allows it.
|
1976
|
-
|
1977
|
-
To use the authentication system, we specify it at the top of our
|
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:
|
1981
|
-
|
1982
|
-
```ruby
|
1983
|
-
class ArticlesController < ApplicationController
|
1984
|
-
|
1985
|
-
http_basic_authenticate_with name: "dhh", password: "secret", except: [:index, :show]
|
1986
|
-
|
1987
|
-
def index
|
1988
|
-
@articles = Article.all
|
1989
|
-
end
|
1990
|
-
|
1991
|
-
# snippet for brevity
|
1992
|
-
```
|
1993
|
-
|
1994
|
-
We also want to allow only authenticated users to delete comments, so in the
|
1995
|
-
`CommentsController` (`app/controllers/comments_controller.rb`) we write:
|
1996
|
-
|
1997
|
-
```ruby
|
1998
|
-
class CommentsController < ApplicationController
|
1999
|
-
|
2000
|
-
http_basic_authenticate_with name: "dhh", password: "secret", only: :destroy
|
2001
|
-
|
2002
|
-
def create
|
2003
|
-
@article = Article.find(params[:article_id])
|
2004
|
-
# ...
|
2005
|
-
end
|
2006
|
-
|
2007
|
-
# snippet for brevity
|
2008
|
-
```
|
2009
|
-
|
2010
|
-
Now if you try to create a new article, you will be greeted with a basic HTTP
|
2011
|
-
Authentication challenge:
|
2012
|
-
|
2013
|
-
![Basic HTTP Authentication Challenge](images/getting_started/challenge.png)
|
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
|
-
|
2029
|
-
What's Next?
|
2030
|
-
------------
|
2031
|
-
|
2032
|
-
Now that you've seen your first Rails application, you should feel free to
|
2033
|
-
update it and experiment on your own. But you don't have to do everything
|
2034
|
-
without help. As you need assistance getting up and running with Rails, feel
|
2035
|
-
free to consult these support resources:
|
2036
|
-
|
2037
|
-
* The [Ruby on Rails Guides](index.html)
|
2038
|
-
* The [Ruby on Rails Tutorial](http://railstutorial.org/book)
|
2039
|
-
* The [Ruby on Rails mailing list](http://groups.google.com/group/rubyonrails-talk)
|
2040
|
-
* The [#rubyonrails](irc://irc.freenode.net/#rubyonrails) channel on irc.freenode.net
|
2041
|
-
|
2042
|
-
Rails also comes with built-in help that you can generate using the rake
|
2043
|
-
command-line utility:
|
2044
|
-
|
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.
|
2051
|
-
|
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.
|
2055
|
-
|
2056
|
-
Configuration Gotchas
|
2057
|
-
---------------------
|
2058
|
-
|
2059
|
-
The easiest way to work with Rails is to store all external data as UTF-8. If
|
2060
|
-
you don't, Ruby libraries and Rails will often be able to convert your native
|
2061
|
-
data into UTF-8, but this doesn't always work reliably, so you're better off
|
2062
|
-
ensuring that all external data is UTF-8.
|
2063
|
-
|
2064
|
-
If you have made a mistake in this area, the most common symptom is a black
|
2065
|
-
diamond with a question mark inside appearing in the browser. Another common
|
2066
|
-
symptom is characters like "ü" appearing instead of "ü". Rails takes a number
|
2067
|
-
of internal steps to mitigate common causes of these problems that can be
|
2068
|
-
automatically detected and corrected. However, if you have external data that is
|
2069
|
-
not stored as UTF-8, it can occasionally result in these kinds of issues that
|
2070
|
-
cannot be automatically detected by Rails and corrected.
|
2071
|
-
|
2072
|
-
Two very common sources of data that are not UTF-8:
|
2073
|
-
|
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.
|