-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgetting_started.html
2071 lines (1878 loc) · 104 KB
/
getting_started.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Getting Started with Rails — Ruby on Rails Guides</title>
<link rel="stylesheet" type="text/css" href="stylesheets/style.css" data-turbolinks-track="reload">
<link rel="stylesheet" type="text/css" href="stylesheets/print.css" media="print">
<link rel="stylesheet" type="text/css" href="stylesheets/syntaxhighlighter/shCore.css" data-turbolinks-track="reload">
<link rel="stylesheet" type="text/css" href="stylesheets/syntaxhighlighter/shThemeRailsGuides.css" data-turbolinks-track="reload">
<link rel="stylesheet" type="text/css" href="stylesheets/fixes.css" data-turbolinks-track="reload">
<link href="images/favicon.ico" rel="shortcut icon" type="image/x-icon" />
<script src="javascripts/syntaxhighlighter.js" data-turbolinks-track="reload"></script>
<script src="javascripts/turbolinks.js" data-turbolinks-track="reload"></script>
<script src="javascripts/guides.js" data-turbolinks-track="reload"></script>
<script src="javascripts/responsive-tables.js" data-turbolinks-track="reload"></script>
</head>
<body class="guide">
<div>
<img src="images/edge_badge.png" alt="edge-badge" id="edge-badge" />
</div>
<div id="topNav">
<div class="wrapper">
<strong class="more-info-label">Veja mais em <a href="http://rubyonrails.org/">rubyonrails.org:</a> </strong>
<span class="red-button more-info-button">
Mais Ruby on Rails
</span>
<ul class="more-info-links s-hidden">
<li class="more-info"><a href="https://weblog.rubyonrails.org/">Blog</a></li>
<li class="more-info"><a href="https://guides.rubyonrails.org/">Guia</a></li>
<li class="more-info"><a href="http://api.rubyonrails.org/">API</a></li>
<li class="more-info"><a href="https://stackoverflow.com/questions/tagged/ruby-on-rails">Pedir ajuda</a></li>
<li class="more-info"><a href="https://github.com/rails/rails">Contribuir no GitHub</a></li>
</ul>
</div>
</div>
<div id="header">
<div class="wrapper clearfix">
<h1><a href="index.html" title="Return to home page">Guides.rubyonrails.org</a></h1>
<ul class="nav">
<li><a class="nav-item" href="index.html">Home</a></li>
<li class="guides-index guides-index-large">
<a href="index.html" id="guidesMenu" class="guides-index-item nav-item">Guias</a>
<div id="guides" class="clearfix" style="display: none;">
<hr />
<div class="guides-section-container">
<div class="guides-section">
<dt>Comece Aqui</dt>
</div>
<div class="guides-section">
<dt>Models</dt>
</div>
<div class="guides-section">
<dt>Views</dt>
</div>
<div class="guides-section">
<dt>Controllers</dt>
</div>
<div class="guides-section">
<dt>Other Components</dt>
</div>
<div class="guides-section">
<dt>Digging Deeper</dt>
</div>
<div class="guides-section">
<dt>Extending Rails</dt>
<dd><a href="rails_on_rack.html">Rails on Rack</a></dd>
<dd><a href="generators.html">Creating and Customizing Rails Generators & Templates</a></dd>
</div>
<div class="guides-section">
<dt>Contributions</dt>
<dd><a href="contributing_to_ruby_on_rails.html">Contributing to Ruby on Rails</a></dd>
<dd><a href="api_documentation_guidelines.html">API Documentation Guidelines</a></dd>
<dd><a href="ruby_on_rails_guides_guidelines.html">Guides Guidelines</a></dd>
</div>
<div class="guides-section">
<dt>Policies</dt>
<dd><a href="maintenance_policy.html">Maintenance Policy</a></dd>
</div>
<div class="guides-section">
<dt>Release Notes</dt>
<dd><a href="upgrading_ruby_on_rails.html">Upgrading Ruby on Rails</a></dd>
<dd><a href="5_2_release_notes.html">Version 5.2 - April 2018</a></dd>
<dd><a href="5_1_release_notes.html">Version 5.1 - April 2017</a></dd>
<dd><a href="5_0_release_notes.html">Version 5.0 - June 2016</a></dd>
<dd><a href="4_2_release_notes.html">Version 4.2 - December 2014</a></dd>
<dd><a href="4_1_release_notes.html">Version 4.1 - April 2014</a></dd>
<dd><a href="4_0_release_notes.html">Version 4.0 - June 2013</a></dd>
<dd><a href="3_2_release_notes.html">Version 3.2 - January 2012</a></dd>
<dd><a href="3_1_release_notes.html">Version 3.1 - August 2011</a></dd>
<dd><a href="3_0_release_notes.html">Version 3.0 - August 2010</a></dd>
<dd><a href="2_3_release_notes.html">Version 2.3 - March 2009</a></dd>
<dd><a href="2_2_release_notes.html">Version 2.2 - November 2008</a></dd>
</div>
</div>
</div>
</li>
<li><a class="nav-item" href="contributing_to_ruby_on_rails.html">Contribua</a></li>
<li class="guides-index guides-index-small">
<select class="guides-index-item nav-item">
<option value="index.html">Guias</option>
<optgroup label="Comece Aqui">
</optgroup>
<optgroup label="Models">
</optgroup>
<optgroup label="Views">
</optgroup>
<optgroup label="Controllers">
</optgroup>
<optgroup label="Other Components">
</optgroup>
<optgroup label="Digging Deeper">
</optgroup>
<optgroup label="Extending Rails">
<option value="rails_on_rack.html">Rails on Rack</option>
<option value="generators.html">Creating and Customizing Rails Generators & Templates</option>
</optgroup>
<optgroup label="Contributions">
<option value="contributing_to_ruby_on_rails.html">Contributing to Ruby on Rails</option>
<option value="api_documentation_guidelines.html">API Documentation Guidelines</option>
<option value="ruby_on_rails_guides_guidelines.html">Guides Guidelines</option>
</optgroup>
<optgroup label="Policies">
<option value="maintenance_policy.html">Maintenance Policy</option>
</optgroup>
<optgroup label="Release Notes">
<option value="upgrading_ruby_on_rails.html">Upgrading Ruby on Rails</option>
<option value="5_2_release_notes.html">Version 5.2 - April 2018</option>
<option value="5_1_release_notes.html">Version 5.1 - April 2017</option>
<option value="5_0_release_notes.html">Version 5.0 - June 2016</option>
<option value="4_2_release_notes.html">Version 4.2 - December 2014</option>
<option value="4_1_release_notes.html">Version 4.1 - April 2014</option>
<option value="4_0_release_notes.html">Version 4.0 - June 2013</option>
<option value="3_2_release_notes.html">Version 3.2 - January 2012</option>
<option value="3_1_release_notes.html">Version 3.1 - August 2011</option>
<option value="3_0_release_notes.html">Version 3.0 - August 2010</option>
<option value="2_3_release_notes.html">Version 2.3 - March 2009</option>
<option value="2_2_release_notes.html">Version 2.2 - November 2008</option>
</optgroup>
</select>
</li>
</ul>
</div>
</div>
<hr class="hide" />
<div id="feature">
<div class="wrapper">
<h2>Getting Started with Rails</h2><p>This guide covers getting up and running with Ruby on Rails.</p><p>After reading this guide, you will know:</p>
<ul>
<li>How to install Rails, create a new Rails application, and connect your
application to a database.</li>
<li>The general layout of a Rails application.</li>
<li>The basic principles of MVC (Model, View, Controller) and RESTful design.</li>
<li>How to quickly generate the starting pieces of a Rails application.</li>
</ul>
<div id="subCol">
<h3 class="chapter"><img src="images/chapters_icon.gif" alt="" />Chapters</h3>
<ol class="chapters">
<li><a href="#guide-assumptions">Guide Assumptions</a></li>
<li><a href="#what-is-rails-questionmark">What is Rails?</a></li>
<li>
<a href="#creating-a-new-rails-project">Creating a New Rails Project</a>
<ul>
<li><a href="#installing-rails">Installing Rails</a></li>
<li><a href="#creating-the-blog-application">Creating the Blog Application</a></li>
</ul>
</li>
<li>
<a href="#hello-rails-bang">Hello, Rails!</a>
<ul>
<li><a href="#starting-up-the-web-server">Starting up the Web Server</a></li>
<li><a href="#say-hello-rails">Say "Hello", Rails</a></li>
<li><a href="#setting-the-application-home-page">Setting the Application Home Page</a></li>
</ul>
</li>
<li>
<a href="#getting-up-and-running">Getting Up and Running</a>
<ul>
<li><a href="#laying-down-the-groundwork">Laying down the groundwork</a></li>
<li><a href="#the-first-form">The first form</a></li>
<li><a href="#creating-articles">Creating articles</a></li>
<li><a href="#creating-the-article-model">Creating the Article model</a></li>
<li><a href="#running-a-migration">Running a Migration</a></li>
<li><a href="#saving-data-in-the-controller">Saving data in the controller</a></li>
<li><a href="#showing-articles">Showing Articles</a></li>
<li><a href="#listing-all-articles">Listing all articles</a></li>
<li><a href="#adding-links">Adding links</a></li>
<li><a href="#adding-some-validation">Adding Some Validation</a></li>
<li><a href="#updating-articles">Updating Articles</a></li>
<li><a href="#using-partials-to-clean-up-duplication-in-views">Using partials to clean up duplication in views</a></li>
<li><a href="#deleting-articles">Deleting Articles</a></li>
</ul>
</li>
<li>
<a href="#adding-a-second-model">Adding a Second Model</a>
<ul>
<li><a href="#generating-a-model">Generating a Model</a></li>
<li><a href="#associating-models">Associating Models</a></li>
<li><a href="#adding-a-route-for-comments">Adding a Route for Comments</a></li>
<li><a href="#generating-a-controller">Generating a Controller</a></li>
</ul>
</li>
<li>
<a href="#refactoring">Refactoring</a>
<ul>
<li><a href="#rendering-partial-collections">Rendering Partial Collections</a></li>
<li><a href="#rendering-a-partial-form">Rendering a Partial Form</a></li>
</ul>
</li>
<li>
<a href="#deleting-comments">Deleting Comments</a>
<ul>
<li><a href="#deleting-associated-objects">Deleting Associated Objects</a></li>
</ul>
</li>
<li>
<a href="#security">Security</a>
<ul>
<li><a href="#basic-authentication">Basic Authentication</a></li>
<li><a href="#other-security-considerations">Other Security Considerations</a></li>
</ul>
</li>
<li><a href="#what-s-next-questionmark">What's Next?</a></li>
<li><a href="#configuration-gotchas">Configuration Gotchas</a></li>
</ol>
</div>
</div>
</div>
<div id="container">
<div class="wrapper">
<div id="mainCol">
<h3 id="guide-assumptions"><a class="anchorlink" href="#guide-assumptions">1 Guide Assumptions</a></h3><p>This guide is designed for beginners who want to get started with a Rails
application from scratch. It does not assume that you have any prior experience
with Rails.</p><p>Rails is a web application framework running on the Ruby programming language.
If you have no prior experience with Ruby, you will find a very steep learning
curve diving straight into Rails. There are several curated lists of online resources
for learning Ruby:</p>
<ul>
<li><a href="https://www.ruby-lang.org/en/documentation/">Official Ruby Programming Language website</a></li>
<li><a href="https://github.com/vhf/free-programming-books/blob/master/free-programming-books.md#ruby">List of Free Programming Books</a></li>
</ul>
<p>Be aware that some resources, while still excellent, cover versions of Ruby as old as
1.6, and commonly 1.8, and will not include some syntax that you will see in day-to-day
development with Rails.</p><h3 id="what-is-rails-questionmark"><a class="anchorlink" href="#what-is-rails-questionmark">2 What is Rails?</a></h3><p>Rails is a web application development framework written in the Ruby programming language.
It is designed to make programming web applications easier by making assumptions
about what every developer needs to get started. It allows you to write less
code while accomplishing more than many other languages and frameworks.
Experienced Rails developers also report that it makes web application
development more fun.</p><p>Rails is opinionated software. It makes the assumption that there is a "best"
way to do things, and it's designed to encourage that way - and in some cases to
discourage alternatives. If you learn "The Rails Way" you'll probably discover a
tremendous increase in productivity. If you persist in bringing old habits from
other languages to your Rails development, and trying to use patterns you
learned elsewhere, you may have a less happy experience.</p><p>The Rails philosophy includes two major guiding principles:</p>
<ul>
<li>
<strong>Don't Repeat Yourself:</strong> DRY is a principle of software development which
states that "Every piece of knowledge must have a single, unambiguous, authoritative
representation within a system." By not writing the same information over and over
again, our code is more maintainable, more extensible, and less buggy.</li>
<li>
<strong>Convention Over Configuration:</strong> Rails has opinions about the best way to do many
things in a web application, and defaults to this set of conventions, rather than
require that you specify minutiae through endless configuration files.</li>
</ul>
<h3 id="creating-a-new-rails-project"><a class="anchorlink" href="#creating-a-new-rails-project">3 Creating a New Rails Project</a></h3><p>The best way to read this guide is to follow it step by step. All steps are
essential to run this example application and no additional code or steps are
needed.</p><p>By following along with this guide, you'll create a Rails project called
<code>blog</code>, a (very) simple weblog. Before you can start building the application,
you need to make sure that you have Rails itself installed.</p><div class="info"><p>The examples below use <code>$</code> to represent your terminal prompt in a UNIX-like OS,
though it may have been customized to appear differently. If you are using Windows,
your prompt will look something like <code>c:\source_code></code></p></div><h4 id="installing-rails"><a class="anchorlink" href="#installing-rails">3.1 Installing Rails</a></h4><p>Before you install Rails, you should check to make sure that your system has the
proper prerequisites installed. These include Ruby and SQLite3.</p><p>Open up a command line prompt. On macOS open Terminal.app, on Windows choose
"Run" from your Start menu and type 'cmd.exe'. Any commands prefaced with a
dollar sign <code>$</code> should be run in the command line. Verify that you have a
current version of Ruby installed:</p><div class="code_container">
<pre class="brush: plain; gutter: false; toolbar: false">
$ ruby -v
ruby 2.5.0
</pre>
</div>
<p>Rails requires Ruby version 2.4.1 or later. If the version number returned is
less than that number, you'll need to install a fresh copy of Ruby.</p><div class="info"><p>To quickly install Ruby and Ruby on Rails on your system in Windows, you can use
<a href="http://railsinstaller.org">Rails Installer</a>. For more installation methods for most
Operating Systems take a look at <a href="https://www.ruby-lang.org/en/documentation/installation/">ruby-lang.org</a>.</p></div><p>If you are working on Windows, you should also install the
<a href="https://rubyinstaller.org/downloads/">Ruby Installer Development Kit</a>.</p><p>You will also need an installation of the SQLite3 database.
Many popular UNIX-like OSes ship with an acceptable version of SQLite3.
On Windows, if you installed Rails through Rails Installer, you
already have SQLite installed. Others can find installation instructions
at the <a href="https://www.sqlite.org">SQLite3 website</a>.
Verify that it is correctly installed and in your PATH:</p><div class="code_container">
<pre class="brush: plain; gutter: false; toolbar: false">
$ sqlite3 --version
</pre>
</div>
<p>The program should report its version.</p><p>To install Rails, use the <code>gem install</code> command provided by RubyGems:</p><div class="code_container">
<pre class="brush: plain; gutter: false; toolbar: false">
$ gem install rails
</pre>
</div>
<p>To verify that you have everything installed correctly, you should be able to
run the following:</p><div class="code_container">
<pre class="brush: plain; gutter: false; toolbar: false">
$ rails --version
</pre>
</div>
<p>If it says something like "Rails 5.2.1", you are ready to continue.</p><h4 id="creating-the-blog-application"><a class="anchorlink" href="#creating-the-blog-application">3.2 Creating the Blog Application</a></h4><p>Rails comes with a number of scripts called generators that are designed to make
your development life easier by creating everything that's necessary to start
working on a particular task. One of these is the new application generator,
which will provide you with the foundation of a fresh Rails application so that
you don't have to write it yourself.</p><p>To use this generator, open a terminal, navigate to a directory where you have
rights to create files, and type:</p><div class="code_container">
<pre class="brush: plain; gutter: false; toolbar: false">
$ rails new blog
</pre>
</div>
<p>This will create a Rails application called Blog in a <code>blog</code> directory and
install the gem dependencies that are already mentioned in <code>Gemfile</code> using
<code>bundle install</code>.</p><div class="note"><p>If you're using Windows Subsystem for Linux then there are currently some
limitations on file system notifications that mean you should disable the <code>spring</code>
and <code>listen</code> gems which you can do by running <code>rails new blog --skip-spring --skip-listen</code>.</p></div><div class="info"><p>You can see all of the command line options that the Rails application
builder accepts by running <code>rails new -h</code>.</p></div><p>After you create the blog application, switch to its folder:</p><div class="code_container">
<pre class="brush: plain; gutter: false; toolbar: false">
$ cd blog
</pre>
</div>
<p>The <code>blog</code> directory has a number of auto-generated files and folders that make
up the structure of a Rails application. Most of the work in this tutorial will
happen in the <code>app</code> folder, but here's a basic rundown on the function of each
of the files and folders that Rails created by default:</p>
<table>
<thead>
<tr>
<th>File/Folder</th>
<th>Purpose</th>
</tr>
</thead>
<tbody>
<tr>
<td>app/</td>
<td>Contains the controllers, models, views, helpers, mailers, channels, jobs, and assets for your application. You'll focus on this folder for the remainder of this guide.</td>
</tr>
<tr>
<td>bin/</td>
<td>Contains the rails script that starts your app and can contain other scripts you use to setup, update, deploy, or run your application.</td>
</tr>
<tr>
<td>config/</td>
<td>Configure your application's routes, database, and more. This is covered in more detail in <a href="configuring.html">Configuring Rails Applications</a>.</td>
</tr>
<tr>
<td>config.ru</td>
<td>Rack configuration for Rack based servers used to start the application. For more information about Rack, see the <a href="https://rack.github.io/">Rack website</a>.</td>
</tr>
<tr>
<td>db/</td>
<td>Contains your current database schema, as well as the database migrations.</td>
</tr>
<tr>
<td>Gemfile<br>Gemfile.lock</td>
<td>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 <a href="https://bundler.io">Bundler website</a>.</td>
</tr>
<tr>
<td>lib/</td>
<td>Extended modules for your application.</td>
</tr>
<tr>
<td>log/</td>
<td>Application log files.</td>
</tr>
<tr>
<td>package.json</td>
<td>This file allows you to specify what npm dependencies are needed for your Rails application. This file is used by Yarn. For more information about Yarn, see the <a href="https://yarnpkg.com/lang/en/">Yarn website</a>.</td>
</tr>
<tr>
<td>public/</td>
<td>The only folder seen by the world as-is. Contains static files and compiled assets.</td>
</tr>
<tr>
<td>Rakefile</td>
<td>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 <code>Rakefile</code>, you should add your own tasks by adding files to the <code>lib/tasks</code> directory of your application.</td>
</tr>
<tr>
<td>README.md</td>
<td>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.</td>
</tr>
<tr>
<td>storage/</td>
<td>Active Storage files for Disk Service. This is covered in <a href="active_storage_overview.html">Active Storage Overview</a>.</td>
</tr>
<tr>
<td>test/</td>
<td>Unit tests, fixtures, and other test apparatus. These are covered in <a href="testing.html">Testing Rails Applications</a>.</td>
</tr>
<tr>
<td>tmp/</td>
<td>Temporary files (like cache and pid files).</td>
</tr>
<tr>
<td>vendor/</td>
<td>A place for all third-party code. In a typical Rails application this includes vendored gems.</td>
</tr>
<tr>
<td>.gitignore</td>
<td>This file tells git which files (or patterns) it should ignore. See <a href="https://help.github.com/articles/ignoring-files">GitHub - Ignoring files</a> for more info about ignoring files.</td>
</tr>
<tr>
<td>.ruby-version</td>
<td>This file contains the default Ruby version.</td>
</tr>
</tbody>
</table>
<h3 id="hello-rails-bang"><a class="anchorlink" href="#hello-rails-bang">4 Hello, Rails!</a></h3><p>To begin with, let's get some text up on screen quickly. To do this, you need to
get your Rails application server running.</p><h4 id="starting-up-the-web-server"><a class="anchorlink" href="#starting-up-the-web-server">4.1 Starting up the Web Server</a></h4><p>You actually have a functional Rails application already. To see it, you need to
start a web server on your development machine. You can do this by running the
following in the <code>blog</code> directory:</p><div class="code_container">
<pre class="brush: plain; gutter: false; toolbar: false">
$ rails server
</pre>
</div>
<div class="info"><p>If you are using Windows, you have to pass the scripts under the <code>bin</code>
folder directly to the Ruby interpreter e.g. <code>ruby bin\rails server</code>.</p></div><div class="info"><p>Compiling CoffeeScript and JavaScript asset compression requires you
have a JavaScript runtime available on your system, in the absence
of a runtime you will see an <code>execjs</code> error during asset compilation.
Usually macOS and Windows come with a JavaScript runtime installed.
Rails adds the <code>mini_racer</code> gem to the generated <code>Gemfile</code> in a
commented line for new apps and you can uncomment if you need it.
<code>therubyrhino</code> is the recommended runtime for JRuby users and is added by
default to the <code>Gemfile</code> in apps generated under JRuby. You can investigate
all the supported runtimes at <a href="https://github.com/rails/execjs#readme">ExecJS</a>.</p></div><p>This will fire up Puma, a web server distributed with Rails by default. To see
your application in action, open a browser window and navigate to
<a href="http://localhost:3000">http://localhost:3000</a>. You should see the Rails default information page:</p><p><img src="images/getting_started/rails_welcome.png" alt="Welcome aboard screenshot"></p><div class="info"><p>To stop the web server, hit Ctrl+C in the terminal window where it's
running. To verify the server has stopped you should see your command prompt
cursor again. For most UNIX-like systems including macOS this will be a
dollar sign <code>$</code>. In development mode, Rails does not generally require you to
restart the server; changes you make in files will be automatically picked up by
the server.</p></div><p>The "Welcome aboard" page is the <em>smoke test</em> for a new Rails application: it
makes sure that you have your software configured correctly enough to serve a
page.</p><h4 id="say-hello-rails"><a class="anchorlink" href="#say-hello-rails">4.2 Say "Hello", Rails</a></h4><p>To get Rails saying "Hello", you need to create at minimum a <em>controller</em> and a
<em>view</em>.</p><p>A controller's purpose is to receive specific requests for the application.
<em>Routing</em> decides which controller receives which requests. Often, there is more
than one route to each controller, and different routes can be served by
different <em>actions</em>. Each action's purpose is to collect information to provide
it to a view.</p><p>A view's purpose is to display this information in a human readable format. An
important distinction to make is that it is the <em>controller</em>, not the view,
where information is collected. The view should just display that information.
By default, view templates are written in a language called eRuby (Embedded
Ruby) which is processed by the request cycle in Rails before being sent to the
user.</p><p>To create a new controller, you will need to run the "controller" generator and
tell it you want a controller called "Welcome" with an action called "index",
just like this:</p><div class="code_container">
<pre class="brush: plain; gutter: false; toolbar: false">
$ rails generate controller Welcome index
</pre>
</div>
<p>Rails will create several files and a route for you.</p><div class="code_container">
<pre class="brush: plain; gutter: false; toolbar: false">
create app/controllers/welcome_controller.rb
route get 'welcome/index'
invoke erb
create app/views/welcome
create app/views/welcome/index.html.erb
invoke test_unit
create test/controllers/welcome_controller_test.rb
invoke helper
create app/helpers/welcome_helper.rb
invoke test_unit
invoke assets
invoke scss
create app/assets/stylesheets/welcome.scss
</pre>
</div>
<p>Most important of these are of course the controller, located at
<code>app/controllers/welcome_controller.rb</code> and the view, located at
<code>app/views/welcome/index.html.erb</code>.</p><p>Open the <code>app/views/welcome/index.html.erb</code> file in your text editor. Delete all
of the existing code in the file, and replace it with the following single line
of code:</p><div class="code_container">
<pre class="brush: xml; gutter: false; toolbar: false">
<h1>Hello, Rails!</h1>
</pre>
</div>
<h4 id="setting-the-application-home-page"><a class="anchorlink" href="#setting-the-application-home-page">4.3 Setting the Application Home Page</a></h4><p>Now that we have made the controller and view, we need to tell Rails when we
want "Hello, Rails!" to show up. In our case, we want it to show up when we
navigate to the root URL of our site, <a href="http://localhost:3000">http://localhost:3000</a>. At the moment,
"Welcome aboard" is occupying that spot.</p><p>Next, you have to tell Rails where your actual home page is located.</p><p>Open the file <code>config/routes.rb</code> in your editor.</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
Rails.application.routes.draw do
get 'welcome/index'
# For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
end
</pre>
</div>
<p>This is your application's <em>routing file</em> which holds entries in a special
<a href="https://en.wikipedia.org/wiki/Domain-specific_language">DSL (domain-specific language)</a>
that tells Rails how to connect incoming requests to
controllers and actions.
Edit this file by adding the line of code <code>root 'welcome#index'</code>.
It should look something like the following:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
Rails.application.routes.draw do
get 'welcome/index'
root 'welcome#index'
end
</pre>
</div>
<p><code>root 'welcome#index'</code> tells Rails to map requests to the root of the
application to the welcome controller's index action and <code>get 'welcome/index'</code>
tells Rails to map requests to <a href="http://localhost:3000/welcome/index">http://localhost:3000/welcome/index</a> to the
welcome controller's index action. This was created earlier when you ran the
controller generator (<code>rails generate controller Welcome index</code>).</p><p>Launch the web server again if you stopped it to generate the controller (<code>rails
server</code>) and navigate to <a href="http://localhost:3000">http://localhost:3000</a> in your browser. You'll see the
"Hello, Rails!" message you put into <code>app/views/welcome/index.html.erb</code>,
indicating that this new route is indeed going to <code>WelcomeController</code>'s <code>index</code>
action and is rendering the view correctly.</p><div class="info"><p>For more information about routing, refer to <a href="routing.html">Rails Routing from the Outside In</a>.</p></div><h3 id="getting-up-and-running"><a class="anchorlink" href="#getting-up-and-running">5 Getting Up and Running</a></h3><p>Now that you've seen how to create a controller, an action, and a view, let's
create something with a bit more substance.</p><p>In the Blog application, you will now create a new <em>resource</em>. A resource is the
term used for a collection of similar objects, such as articles, people, or
animals.
You can create, read, update, and destroy items for a resource and these
operations are referred to as <em>CRUD</em> operations.</p><p>Rails provides a <code>resources</code> method which can be used to declare a standard REST
resource. You need to add the <em>article resource</em> to the
<code>config/routes.rb</code> so the file will look as follows:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
Rails.application.routes.draw do
get 'welcome/index'
resources :articles
root 'welcome#index'
end
</pre>
</div>
<p>If you run <code>rails routes</code>, you'll see that it has defined routes for all the
standard RESTful actions. The meaning of the prefix column (and other columns)
will be seen later, but for now notice that Rails has inferred the
singular form <code>article</code> and makes meaningful use of the distinction.</p><div class="code_container">
<pre class="brush: plain; gutter: false; toolbar: false">
$ rails routes
Prefix Verb URI Pattern Controller#Action
welcome_index GET /welcome/index(.:format) welcome#index
articles GET /articles(.:format) articles#index
POST /articles(.:format) articles#create
new_article GET /articles/new(.:format) articles#new
edit_article GET /articles/:id/edit(.:format) articles#edit
article GET /articles/:id(.:format) articles#show
PATCH /articles/:id(.:format) articles#update
PUT /articles/:id(.:format) articles#update
DELETE /articles/:id(.:format) articles#destroy
root GET / welcome#index
</pre>
</div>
<p>In the next section, you will add the ability to create new articles in your
application and be able to view them. This is the "C" and the "R" from CRUD:
create and read. The form for doing this will look like this:</p><p><img src="images/getting_started/new_article.png" alt="The new article form"></p><p>It will look a little basic for now, but that's ok. We'll look at improving the
styling for it afterwards.</p><h4 id="laying-down-the-groundwork"><a class="anchorlink" href="#laying-down-the-groundwork">5.1 Laying down the groundwork</a></h4><p>Firstly, you need a place within the application to create a new article. A
great place for that would be at <code>/articles/new</code>. With the route already
defined, requests can now be made to <code>/articles/new</code> in the application.
Navigate to <a href="http://localhost:3000/articles/new">http://localhost:3000/articles/new</a> and you'll see a routing
error:</p><p><img src="images/getting_started/routing_error_no_controller.png" alt="Another routing error, uninitialized constant ArticlesController"></p><p>This error occurs because the route needs to have a controller defined in order
to serve the request. The solution to this particular problem is simple: create
a controller called <code>ArticlesController</code>. You can do this by running this
command:</p><div class="code_container">
<pre class="brush: plain; gutter: false; toolbar: false">
$ rails generate controller Articles
</pre>
</div>
<p>If you open up the newly generated <code>app/controllers/articles_controller.rb</code>
you'll see a fairly empty controller:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class ArticlesController < ApplicationController
end
</pre>
</div>
<p>A controller is simply a class that is defined to inherit from
<code>ApplicationController</code>.
It's inside this class that you'll define methods that will become the actions
for this controller. These actions will perform CRUD operations on the articles
within our system.</p><div class="note"><p>There are <code>public</code>, <code>private</code> and <code>protected</code> methods in Ruby,
but only <code>public</code> methods can be actions for controllers.
For more details check out <a href="http://www.ruby-doc.org/docs/ProgrammingRuby/">Programming Ruby</a>.</p></div><p>If you refresh <a href="http://localhost:3000/articles/new">http://localhost:3000/articles/new</a> now, you'll get a new error:</p><p><img src="images/getting_started/unknown_action_new_for_articles.png" alt="Unknown action new for ArticlesController!"></p><p>This error indicates that Rails cannot find the <code>new</code> action inside the
<code>ArticlesController</code> that you just generated. This is because when controllers
are generated in Rails they are empty by default, unless you tell it
your desired actions during the generation process.</p><p>To manually define an action inside a controller, all you need to do is to
define a new method inside the controller. Open
<code>app/controllers/articles_controller.rb</code> and inside the <code>ArticlesController</code>
class, define the <code>new</code> method so that your controller now looks like this:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class ArticlesController < ApplicationController
def new
end
end
</pre>
</div>
<p>With the <code>new</code> method defined in <code>ArticlesController</code>, if you refresh
<a href="http://localhost:3000/articles/new">http://localhost:3000/articles/new</a> you'll see another error:</p><p><img src="images/getting_started/template_is_missing_articles_new.png" alt="Template is missing for articles/new"></p><p>You're getting this error now because Rails expects plain actions like this one
to have views associated with them to display their information. With no view
available, Rails will raise an exception.</p><p>Let's look at the full error message again:</p>
<blockquote>
<p>ArticlesController#new is missing a template for this request format and variant. request.formats: ["text/html"] request.variant: [] NOTE! For XHR/Ajax or API requests, this action would normally respond with 204 No Content: an empty white screen. Since you're loading it in a web browser, we assume that you expected to actually render a template, not… nothing, so we're showing an error to be extra-clear. If you expect 204 No Content, carry on. That's what you'll get from an XHR or API request. Give it a shot.</p>
</blockquote>
<p>That's quite a lot of text! Let's quickly go through and understand what each
part of it means.</p><p>The first part identifies which template is missing. In this case, it's the
<code>articles/new</code> template. Rails will first look for this template. If not found,
then it will attempt to load a template called <code>application/new</code>. It looks for
one here because the <code>ArticlesController</code> inherits from <code>ApplicationController</code>.</p><p>The next part of the message contains <code>request.formats</code> which specifies
the format of template to be served in response. It is set to <code>text/html</code> as we
requested this page via browser, so Rails is looking for an HTML template.
<code>request.variant</code> specifies what kind of physical devices would be served by
the response and helps Rails determine which template to use in the response.
It is empty because no information has been provided.</p><p>The simplest template that would work in this case would be one located at
<code>app/views/articles/new.html.erb</code>. The extension of this file name is important:
the first extension is the <em>format</em> of the template, and the second extension
is the <em>handler</em> that will be used to render the template. Rails is attempting
to find a template called <code>articles/new</code> within <code>app/views</code> for the
application. The format for this template can only be <code>html</code> and the default
handler for HTML is <code>erb</code>. Rails uses other handlers for other formats.
<code>builder</code> handler is used to build XML templates and <code>coffee</code> handler uses
CoffeeScript to build JavaScript templates. Since you want to create a new
HTML form, you will be using the <code>ERB</code> language which is designed to embed Ruby
in HTML.</p><p>Therefore the file should be called <code>articles/new.html.erb</code> and needs to be
located inside the <code>app/views</code> directory of the application.</p><p>Go ahead now and create a new file at <code>app/views/articles/new.html.erb</code> and
write this content in it:</p><div class="code_container">
<pre class="brush: xml; gutter: false; toolbar: false">
<h1>New Article</h1>
</pre>
</div>
<p>When you refresh <a href="http://localhost:3000/articles/new">http://localhost:3000/articles/new</a> you'll now see that the
page has a title. The route, controller, action, and view are now working
harmoniously! It's time to create the form for a new article.</p><h4 id="the-first-form"><a class="anchorlink" href="#the-first-form">5.2 The first form</a></h4><p>To create a form within this template, you will use a <em>form
builder</em>. The primary form builder for Rails is provided by a helper
method called <code>form_with</code>. To use this method, add this code into
<code>app/views/articles/new.html.erb</code>:</p><div class="code_container">
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
<%= form_with scope: :article, local: true do |form| %>
<p>
<%= form.label :title %><br>
<%= form.text_field :title %>
</p>
<p>
<%= form.label :text %><br>
<%= form.text_area :text %>
</p>
<p>
<%= form.submit %>
</p>
<% end %>
</pre>
</div>
<p>If you refresh the page now, you'll see the exact same form from our example above.
Building forms in Rails is really just that easy!</p><p>When you call <code>form_with</code>, you pass it an identifying scope for this
form. In this case, it's the symbol <code>:article</code>. This tells the <code>form_with</code>
helper what this form is for. Inside the block for this method, the
<code>FormBuilder</code> object - represented by <code>form</code> - is used to build two labels and two
text fields, one each for the title and text of an article. Finally, a call to
<code>submit</code> on the <code>form</code> object will create a submit button for the form.</p><p>There's one problem with this form though. If you inspect the HTML that is
generated, by viewing the source of the page, you will see that the <code>action</code>
attribute for the form is pointing at <code>/articles/new</code>. This is a problem because
this route goes to the very page that you're on right at the moment, and that
route should only be used to display the form for a new article.</p><p>The form needs to use a different URL in order to go somewhere else.
This can be done quite simply with the <code>:url</code> option of <code>form_with</code>.
Typically in Rails, the action that is used for new form submissions
like this is called "create", and so the form should be pointed to that action.</p><p>Edit the <code>form_with</code> line inside <code>app/views/articles/new.html.erb</code> to look like
this:</p><div class="code_container">
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
<%= form_with scope: :article, url: articles_path, local: true do |form| %>
</pre>
</div>
<p>In this example, the <code>articles_path</code> helper is passed to the <code>:url</code> option.
To see what Rails will do with this, we look back at the output of
<code>rails routes</code>:</p><div class="code_container">
<pre class="brush: plain; gutter: false; toolbar: false">
$ rails routes
Prefix Verb URI Pattern Controller#Action
welcome_index GET /welcome/index(.:format) welcome#index
articles GET /articles(.:format) articles#index
POST /articles(.:format) articles#create
new_article GET /articles/new(.:format) articles#new
edit_article GET /articles/:id/edit(.:format) articles#edit
article GET /articles/:id(.:format) articles#show
PATCH /articles/:id(.:format) articles#update
PUT /articles/:id(.:format) articles#update
DELETE /articles/:id(.:format) articles#destroy
root GET / welcome#index
</pre>
</div>
<p>The <code>articles_path</code> helper tells Rails to point the form to the URI Pattern
associated with the <code>articles</code> prefix; and the form will (by default) send a
<code>POST</code> request to that route. This is associated with the <code>create</code> action of
the current controller, the <code>ArticlesController</code>.</p><p>With the form and its associated route defined, you will be able to fill in the
form and then click the submit button to begin the process of creating a new
article, so go ahead and do that. When you submit the form, you should see a
familiar error:</p><p><img src="images/getting_started/unknown_action_create_for_articles.png" alt="Unknown action create for ArticlesController"></p><p>You now need to create the <code>create</code> action within the <code>ArticlesController</code> for
this to work.</p><div class="note"><p>By default <code>form_with</code> submits forms using Ajax thereby skipping full page
redirects. To make this guide easier to get into we've disabled that with
<code>local: true</code> for now.</p></div><h4 id="creating-articles"><a class="anchorlink" href="#creating-articles">5.3 Creating articles</a></h4><p>To make the "Unknown action" go away, you can define a <code>create</code> action within
the <code>ArticlesController</code> class in <code>app/controllers/articles_controller.rb</code>,
underneath the <code>new</code> action, as shown:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class ArticlesController < ApplicationController
def new
end
def create
end
end
</pre>
</div>
<p>If you re-submit the form now, you may not see any change on the page. Don't worry!
This is because Rails by default returns <code>204 No Content</code> response for an action if
we don't specify what the response should be. We just added the <code>create</code> action
but didn't specify anything about how the response should be. In this case, the
<code>create</code> action should save our new article to the database.</p><p>When a form is submitted, the fields of the form are sent to Rails as
<em>parameters</em>. These parameters can then be referenced inside the controller
actions, typically to perform a particular task. To see what these parameters
look like, change the <code>create</code> action to this:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
def create
render plain: params[:article].inspect
end
</pre>
</div>
<p>The <code>render</code> method here is taking a very simple hash with a key of <code>:plain</code> and
value of <code>params[:article].inspect</code>. The <code>params</code> method is the object which
represents the parameters (or fields) coming in from the form. The <code>params</code>
method returns an <code>ActionController::Parameters</code> object, which
allows you to access the keys of the hash using either strings or symbols. In
this situation, the only parameters that matter are the ones from the form.</p><div class="info"><p>Ensure you have a firm grasp of the <code>params</code> method, as you'll use it fairly regularly. Let's consider an example URL: <strong><a href="http://www.example.com/?username=dhh&[email protected]">http://www.example.com/?username=dhh&[email protected]</a></strong>. In this URL, <code>params[:username]</code> would equal "dhh" and <code>params[:email]</code> would equal "<a href="mailto:[email protected]">[email protected]</a>".</p></div><p>If you re-submit the form one more time, you'll see something that looks like the following:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
<ActionController::Parameters {"title"=>"First Article!", "text"=>"This is my first article."} permitted: false>
</pre>
</div>
<p>This action is now displaying the parameters for the article that are coming in
from the form. However, this isn't really all that helpful. Yes, you can see the
parameters but nothing in particular is being done with them.</p><h4 id="creating-the-article-model"><a class="anchorlink" href="#creating-the-article-model">5.4 Creating the Article model</a></h4><p>Models in Rails use a singular name, and their corresponding database tables
use a plural name. Rails provides a generator for creating models, which most
Rails developers tend to use when creating new models. To create the new model,
run this command in your terminal:</p><div class="code_container">
<pre class="brush: plain; gutter: false; toolbar: false">
$ rails generate model Article title:string text:text
</pre>
</div>
<p>With that command we told Rails that we want an <code>Article</code> model, together
with a <em>title</em> attribute of type string, and a <em>text</em> attribute
of type text. Those attributes are automatically added to the <code>articles</code>
table in the database and mapped to the <code>Article</code> model.</p><p>Rails responded by creating a bunch of files. For now, we're only interested
in <code>app/models/article.rb</code> and <code>db/migrate/20140120191729_create_articles.rb</code>
(your name could be a bit different). The latter is responsible for creating
the database structure, which is what we'll look at next.</p><div class="info"><p>Active Record is smart enough to automatically map column names to model
attributes, which means you don't have to declare attributes inside Rails
models, as that will be done automatically by Active Record.</p></div><h4 id="running-a-migration"><a class="anchorlink" href="#running-a-migration">5.5 Running a Migration</a></h4><p>As we've just seen, <code>rails generate model</code> created a <em>database migration</em> file
inside the <code>db/migrate</code> directory. Migrations are Ruby classes that are
designed to make it simple to create and modify database tables. Rails uses
rake commands to run migrations, and it's possible to undo a migration after
it's been applied to your database. Migration filenames include a timestamp to
ensure that they're processed in the order that they were created.</p><p>If you look in the <code>db/migrate/YYYYMMDDHHMMSS_create_articles.rb</code> file
(remember, yours will have a slightly different name), here's what you'll find:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class CreateArticles < ActiveRecord::Migration[5.0]
def change
create_table :articles do |t|
t.string :title
t.text :text
t.timestamps
end
end
end
</pre>
</div>
<p>The above migration creates a method named <code>change</code> which will be called when
you run this migration. The action defined in this method is also reversible,
which means Rails knows how to reverse the change made by this migration,
in case you want to reverse it later. When you run this migration it will create
an <code>articles</code> table with one string column and a text column. It also creates
two timestamp fields to allow Rails to track article creation and update times.</p><div class="info"><p>For more information about migrations, refer to <a href="active_record_migrations.html">Active Record Migrations</a>.</p></div><p>At this point, you can use a rails command to run the migration:</p><div class="code_container">
<pre class="brush: plain; gutter: false; toolbar: false">
$ rails db:migrate
</pre>
</div>
<p>Rails will execute this migration command and tell you it created the Articles
table.</p><div class="code_container">
<pre class="brush: plain; gutter: false; toolbar: false">
== CreateArticles: migrating ==================================================
-- create_table(:articles)
-> 0.0019s
== CreateArticles: migrated (0.0020s) =========================================
</pre>
</div>
<div class="note"><p>Because you're working in the development environment by default, this
command will apply to the database defined in the <code>development</code> section of your
<code>config/database.yml</code> file. If you would like to execute migrations in another
environment, for instance in production, you must explicitly pass it when
invoking the command: <code>rails db:migrate RAILS_ENV=production</code>.</p></div><h4 id="saving-data-in-the-controller"><a class="anchorlink" href="#saving-data-in-the-controller">5.6 Saving data in the controller</a></h4><p>Back in <code>ArticlesController</code>, we need to change the <code>create</code> action
to use the new <code>Article</code> model to save the data in the database.
Open <code>app/controllers/articles_controller.rb</code> and change the <code>create</code> action to
look like this:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
def create
@article = Article.new(params[:article])
@article.save
redirect_to @article
end
</pre>
</div>
<p>Here's what's going on: every Rails model can be initialized with its
respective attributes, which are automatically mapped to the respective
database columns. In the first line we do just that (remember that
<code>params[:article]</code> contains the attributes we're interested in). Then,
<code>@article.save</code> is responsible for saving the model in the database. Finally,
we redirect the user to the <code>show</code> action, which we'll define later.</p><div class="info"><p>You might be wondering why the <code>A</code> in <code>Article.new</code> 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 <code>Article</code> that is defined in <code>app/models/article.rb</code>. Class names in Ruby must begin with a capital letter.</p></div><div class="info"><p>As we'll see later, <code>@article.save</code> returns a boolean indicating whether
the article was saved or not.</p></div><p>If you now go to <a href="http://localhost:3000/articles/new">http://localhost:3000/articles/new</a> you'll <em>almost</em> be able
to create an article. Try it! You should get an error that looks like this:</p><p><img src="images/getting_started/forbidden_attributes_for_new_article.png" alt="Forbidden attributes for new article"></p><p>Rails has several security features that help you write secure applications,
and you're running into one of them now. This one is called <a href="action_controller_overview.html#strong-parameters">strong parameters</a>,
which requires us to tell Rails exactly which parameters are allowed into our
controller actions.</p><p>Why do you have to bother? The ability to grab and automatically assign all
controller parameters to your model in one shot makes the programmer's job
easier, but this convenience also allows malicious use. What if a request to
the server was crafted to look like a new article form submit but also included
extra fields with values that violated your application's integrity? They would
be 'mass assigned' into your model and then into the database along with the
good stuff - potentially breaking your application or worse.</p><p>We have to define our permitted controller parameters to prevent wrongful mass
assignment. In this case, we want to both allow and require the <code>title</code> and
<code>text</code> parameters for valid use of <code>create</code>. The syntax for this introduces
<code>require</code> and <code>permit</code>. The change will involve one line in the <code>create</code>
action:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
@article = Article.new(params.require(:article).permit(:title, :text))
</pre>
</div>
<p>This is often factored out into its own method so it can be reused by multiple
actions in the same controller, for example <code>create</code> and <code>update</code>. Above and
beyond mass assignment issues, the method is often made <code>private</code> to make sure
it can't be called outside its intended context. Here is the result:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
def create
@article = Article.new(article_params)
@article.save
redirect_to @article
end
private
def article_params
params.require(:article).permit(:title, :text)
end
</pre>
</div>
<div class="info"><p>For more information, refer to the reference above and
<a href="https://weblog.rubyonrails.org/2012/3/21/strong-parameters/">this blog article about Strong Parameters</a>.</p></div><h4 id="showing-articles"><a class="anchorlink" href="#showing-articles">5.7 Showing Articles</a></h4><p>If you submit the form again now, Rails will complain about not finding the
<code>show</code> action. That's not very useful though, so let's add the <code>show</code> action
before proceeding.</p><p>As we have seen in the output of <code>rails routes</code>, the route for <code>show</code> action is
as follows:</p><div class="code_container">
<pre class="brush: plain; gutter: false; toolbar: false">
article GET /articles/:id(.:format) articles#show
</pre>
</div>
<p>The special syntax <code>:id</code> tells rails that this route expects an <code>:id</code>
parameter, which in our case will be the id of the article.</p><p>As we did before, we need to add the <code>show</code> action in
<code>app/controllers/articles_controller.rb</code> and its respective view.</p><div class="note"><p>A frequent practice is to place the standard CRUD actions in each
controller in the following order: <code>index</code>, <code>show</code>, <code>new</code>, <code>edit</code>, <code>create</code>, <code>update</code>
and <code>destroy</code>. You may use any order you choose, but keep in mind that these
are public methods; as mentioned earlier in this guide, they must be placed
before declaring <code>private</code> visibility in the controller.</p></div><p>Given that, let's add the <code>show</code> action, as follows:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class ArticlesController < ApplicationController
def show
@article = Article.find(params[:id])
end
def new
end
# snippet for brevity
</pre>
</div>
<p>A couple of things to note. We use <code>Article.find</code> to find the article we're
interested in, passing in <code>params[:id]</code> to get the <code>:id</code> parameter from the
request. We also use an instance variable (prefixed with <code>@</code>) to hold a
reference to the article object. We do this because Rails will pass all instance
variables to the view.</p><p>Now, create a new file <code>app/views/articles/show.html.erb</code> with the following
content:</p><div class="code_container">
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
<p>
<strong>Title:</strong>
<%= @article.title %>
</p>
<p>
<strong>Text:</strong>
<%= @article.text %>
</p>
</pre>
</div>
<p>With this change, you should finally be able to create new articles.
Visit <a href="http://localhost:3000/articles/new">http://localhost:3000/articles/new</a> and give it a try!</p><p><img src="images/getting_started/show_action_for_articles.png" alt="Show action for articles"></p><h4 id="listing-all-articles"><a class="anchorlink" href="#listing-all-articles">5.8 Listing all articles</a></h4><p>We still need a way to list all our articles, so let's do that.
The route for this as per output of <code>rails routes</code> is:</p><div class="code_container">
<pre class="brush: plain; gutter: false; toolbar: false">
articles GET /articles(.:format) articles#index
</pre>
</div>
<p>Add the corresponding <code>index</code> action for that route inside the
<code>ArticlesController</code> in the <code>app/controllers/articles_controller.rb</code> file.
When we write an <code>index</code> action, the usual practice is to place it as the
first method in the controller. Let's do it:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class ArticlesController < ApplicationController
def index
@articles = Article.all
end
def show
@article = Article.find(params[:id])
end
def new
end
# snippet for brevity
</pre>
</div>
<p>And then finally, add the view for this action, located at
<code>app/views/articles/index.html.erb</code>:</p><div class="code_container">
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
<h1>Listing articles</h1>
<table>
<tr>
<th>Title</th>
<th>Text</th>
<th></th>
</tr>
<% @articles.each do |article| %>
<tr>
<td><%= article.title %></td>
<td><%= article.text %></td>
<td><%= link_to 'Show', article_path(article) %></td>
</tr>
<% end %>
</table>
</pre>
</div>
<p>Now if you go to <a href="http://localhost:3000/articles">http://localhost:3000/articles</a> you will see a list of all the
articles that you have created.</p><h4 id="adding-links"><a class="anchorlink" href="#adding-links">5.9 Adding links</a></h4><p>You can now create, show, and list articles. Now let's add some links to
navigate through pages.</p><p>Open <code>app/views/welcome/index.html.erb</code> and modify it as follows:</p><div class="code_container">
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">