-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathaction_controller_overview.html
1276 lines (1166 loc) · 88 KB
/
action_controller_overview.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>Action Controller Overview — 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>
<meta property="og:title" content="Action Controller Overview — Ruby on Rails Guides" />
<meta name="description" content="Action Controller OverviewIn this guide you will learn how controllers work and how they fit into the request cycle in your application.After reading this guide, you will know: How to follow the flow of a request through a controller. How to restrict parameters passed to your controller. How and why to store data in the session or cookies. How to work with filters to execute code during request processing. How to use Action Controller's built-in HTTP authentication. How to stream data directly to the user's browser. How to filter sensitive parameters so they do not appear in the application's log. How to deal with exceptions that may be raised during request processing." />
<meta property="og:description" content="Action Controller OverviewIn this guide you will learn how controllers work and how they fit into the request cycle in your application.After reading this guide, you will know: How to follow the flow of a request through a controller. How to restrict parameters passed to your controller. How and why to store data in the session or cookies. How to work with filters to execute code during request processing. How to use Action Controller's built-in HTTP authentication. How to stream data directly to the user's browser. How to filter sensitive parameters so they do not appear in the application's log. How to deal with exceptions that may be raised during request processing." />
<meta property="og:locale" content="en_US" />
<meta property="og:site_name" content="Ruby on Rails Guides" />
<meta property="og:image" content="https://avatars.githubusercontent.com/u/4223" />
<meta property="og:type" content="website" />
</head>
<body class="guide">
<div id="topNav">
<div class="wrapper">
<strong class="more-info-label">공식 웹사이트 <a href="https://rubyonrails.org/">rubyonrails.org:</a> </strong>
<span class="red-button more-info-button">
루비온레일스 웹사이트
</span>
<ul class="more-info-links s-hidden">
<li class="more-info"><a href="https://weblog.rubyonrails.org/">블로그</a></li>
<li class="more-info"><a href="https://guides.rubyonrails.org/">영문가이드</a></li>
<li class="more-info"><a href="https://api.rubyonrails.org/">레일스API</a></li>
<li class="more-info"><a href="https://stackoverflow.com/questions/tagged/ruby-on-rails">질문하기</a></li>
<li class="more-info"><a href="https://github.com/rails/rails">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">홈</a></li>
<li class="guides-index guides-index-large">
<a href="index.html" id="guidesMenu" class="guides-index-item nav-item">가이드 인덱스</a>
<div id="guides" class="clearfix" style="display: none;">
<hr />
<div class="guides-section-container">
<div class="guides-section">
<dt>시작하면서</dt>
<dd><a href="getting_started.html">레일스로 시작하기</a></dd>
</div>
<div class="guides-section">
<dt>모델</dt>
<dd><a href="active_record_basics.html">액티브 레코드 기본</a></dd>
<dd><a href="active_record_migrations.html">액티브 레코드 마이그레이션</a></dd>
<dd><a href="active_record_validations.html">액티브 레코드 유효성 검증</a></dd>
<dd><a href="active_record_callbacks.html">액티브 레코드 콜백</a></dd>
<dd><a href="association_basics.html">Active Record Associations</a></dd>
<dd><a href="active_record_querying.html">Active Record Query Interface</a></dd>
</div>
<div class="guides-section">
<dt>Views</dt>
<dd><a href="layouts_and_rendering.html">Layouts and Rendering in Rails</a></dd>
<dd><a href="form_helpers.html">Action View Form Helpers</a></dd>
</div>
<div class="guides-section">
<dt>Controllers</dt>
<dd><a href="action_controller_overview.html">Action Controller Overview</a></dd>
<dd><a href="routing.html">Rails Routing from the Outside In</a></dd>
</div>
<div class="guides-section">
<dt>Other Components</dt>
<dd><a href="active_support_core_extensions.html">Active Support Core Extensions</a></dd>
<dd><a href="action_mailer_basics.html">Action Mailer Basics</a></dd>
<dd><a href="active_job_basics.html">Active Job Basics</a></dd>
<dd><a href="active_storage_overview.html">Active Storage Overview</a></dd>
<dd><a href="action_cable_overview.html">Action Cable Overview</a></dd>
</div>
<div class="guides-section">
<dt>Digging Deeper</dt>
<dd><a href="i18n.html">Rails Internationalization (I18n) API</a></dd>
<dd><a href="testing.html">Testing Rails Applications</a></dd>
<dd><a href="security.html">Securing Rails Applications</a></dd>
<dd><a href="debugging_rails_applications.html">Debugging Rails Applications</a></dd>
<dd><a href="configuring.html">Configuring Rails Applications</a></dd>
<dd><a href="command_line.html">The Rails Command Line</a></dd>
<dd><a href="asset_pipeline.html">The Asset Pipeline</a></dd>
<dd><a href="working_with_javascript_in_rails.html">Working with JavaScript in Rails</a></dd>
<dd><a href="autoloading_and_reloading_constants.html">Autoloading and Reloading Constants (Zeitwerk Mode)</a></dd>
<dd><a href="autoloading_and_reloading_constants_classic_mode.html">Autoloading and Reloading Constants (Classic Mode)</a></dd>
<dd><a href="caching_with_rails.html">Caching with Rails: An Overview</a></dd>
<dd><a href="api_app.html">Using Rails for API-only Applications</a></dd>
</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="6_0_release_notes.html">Version 6.0 - August 2019</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">기여하기</a></li>
<li class="guides-index guides-index-small">
<select class="guides-index-item nav-item">
<option value="index.html">가이드 인덱스</option>
<optgroup label="시작하면서">
<option value="getting_started.html">레일스로 시작하기</option>
</optgroup>
<optgroup label="모델">
<option value="active_record_basics.html">액티브 레코드 기본</option>
<option value="active_record_migrations.html">액티브 레코드 마이그레이션</option>
<option value="active_record_validations.html">액티브 레코드 유효성 검증</option>
<option value="active_record_callbacks.html">액티브 레코드 콜백</option>
<option value="association_basics.html">Active Record Associations</option>
<option value="active_record_querying.html">Active Record Query Interface</option>
</optgroup>
<optgroup label="Views">
<option value="layouts_and_rendering.html">Layouts and Rendering in Rails</option>
<option value="form_helpers.html">Action View Form Helpers</option>
</optgroup>
<optgroup label="Controllers">
<option value="action_controller_overview.html">Action Controller Overview</option>
<option value="routing.html">Rails Routing from the Outside In</option>
</optgroup>
<optgroup label="Other Components">
<option value="active_support_core_extensions.html">Active Support Core Extensions</option>
<option value="action_mailer_basics.html">Action Mailer Basics</option>
<option value="active_job_basics.html">Active Job Basics</option>
<option value="active_storage_overview.html">Active Storage Overview</option>
<option value="action_cable_overview.html">Action Cable Overview</option>
</optgroup>
<optgroup label="Digging Deeper">
<option value="i18n.html">Rails Internationalization (I18n) API</option>
<option value="testing.html">Testing Rails Applications</option>
<option value="security.html">Securing Rails Applications</option>
<option value="debugging_rails_applications.html">Debugging Rails Applications</option>
<option value="configuring.html">Configuring Rails Applications</option>
<option value="command_line.html">The Rails Command Line</option>
<option value="asset_pipeline.html">The Asset Pipeline</option>
<option value="working_with_javascript_in_rails.html">Working with JavaScript in Rails</option>
<option value="autoloading_and_reloading_constants.html">Autoloading and Reloading Constants (Zeitwerk Mode)</option>
<option value="autoloading_and_reloading_constants_classic_mode.html">Autoloading and Reloading Constants (Classic Mode)</option>
<option value="caching_with_rails.html">Caching with Rails: An Overview</option>
<option value="api_app.html">Using Rails for API-only Applications</option>
</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="6_0_release_notes.html">Version 6.0 - August 2019</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>Action Controller Overview</h2><p>In this guide you will learn how controllers work and how they fit into the request cycle in your application.</p><p>After reading this guide, you will know:</p>
<ul>
<li>How to follow the flow of a request through a controller.</li>
<li>How to restrict parameters passed to your controller.</li>
<li>How and why to store data in the session or cookies.</li>
<li>How to work with filters to execute code during request processing.</li>
<li>How to use Action Controller's built-in HTTP authentication.</li>
<li>How to stream data directly to the user's browser.</li>
<li>How to filter sensitive parameters so they do not appear in the application's log.</li>
<li>How to deal with exceptions that may be raised during request processing.</li>
</ul>
<div id="subCol">
<h3 class="chapter"><img src="images/chapters_icon.gif" alt="" />Chapters</h3>
<ol class="chapters">
<li><a href="#what-does-a-controller-do-questionmark">What Does a Controller Do?</a></li>
<li><a href="#controller-naming-convention">Controller Naming Convention</a></li>
<li><a href="#methods-and-actions">Methods and Actions</a></li>
<li>
<a href="#parameters">Parameters</a>
<ul>
<li><a href="#hash-and-array-parameters">Hash and Array Parameters</a></li>
<li><a href="#json-parameters">JSON parameters</a></li>
<li><a href="#routing-parameters">Routing Parameters</a></li>
<li><a href="#default-url-options"><code>default_url_options</code></a></li>
<li><a href="#strong-parameters">Strong Parameters</a></li>
</ul>
</li>
<li>
<a href="#session">Session</a>
<ul>
<li><a href="#accessing-the-session">Accessing the Session</a></li>
<li><a href="#the-flash">The Flash</a></li>
</ul>
</li>
<li><a href="#cookies">Cookies</a></li>
<li><a href="#rendering-xml-and-json-data">Rendering XML and JSON data</a></li>
<li>
<a href="#filters">Filters</a>
<ul>
<li><a href="#after-filters-and-around-filters">After Filters and Around Filters</a></li>
<li><a href="#other-ways-to-use-filters">Other Ways to Use Filters</a></li>
</ul>
</li>
<li><a href="#request-forgery-protection">Request Forgery Protection</a></li>
<li>
<a href="#the-request-and-response-objects">The Request and Response Objects</a>
<ul>
<li><a href="#the-request-object">The <code>request</code> Object</a></li>
<li><a href="#the-response-object">The <code>response</code> Object</a></li>
</ul>
</li>
<li>
<a href="#http-authentications">HTTP Authentications</a>
<ul>
<li><a href="#http-basic-authentication">HTTP Basic Authentication</a></li>
<li><a href="#http-digest-authentication">HTTP Digest Authentication</a></li>
</ul>
</li>
<li>
<a href="#streaming-and-file-downloads">Streaming and File Downloads</a>
<ul>
<li><a href="#sending-files">Sending Files</a></li>
<li><a href="#restful-downloads">RESTful Downloads</a></li>
<li><a href="#live-streaming-of-arbitrary-data">Live Streaming of Arbitrary Data</a></li>
</ul>
</li>
<li>
<a href="#log-filtering">Log Filtering</a>
<ul>
<li><a href="#parameters-filtering">Parameters Filtering</a></li>
<li><a href="#redirects-filtering">Redirects Filtering</a></li>
</ul>
</li>
<li>
<a href="#rescue">Rescue</a>
<ul>
<li><a href="#the-default-500-and-404-templates">The Default 500 and 404 Templates</a></li>
<li><a href="#rescue-from"><code>rescue_from</code></a></li>
</ul>
</li>
<li><a href="#force-https-protocol">Force HTTPS protocol</a></li>
</ol>
</div>
</div>
</div>
<div id="container">
<div class="wrapper">
<div id="mainCol">
<h3 id="what-does-a-controller-do-questionmark"><a class="anchorlink" href="#what-does-a-controller-do-questionmark">1 What Does a Controller Do?</a></h3><p>Action Controller is the C in <a href="https://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller">MVC</a>. After the router has determined which controller to use for a request, the controller is responsible for making sense of the request, and producing the appropriate output. Luckily, Action Controller does most of the groundwork for you and uses smart conventions to make this as straightforward as possible.</p><p>For most conventional <a href="https://en.wikipedia.org/wiki/Representational_state_transfer">RESTful</a> applications, the controller will receive the request (this is invisible to you as the developer), fetch or save data from a model, and use a view to create HTML output. If your controller needs to do things a little differently, that's not a problem, this is just the most common way for a controller to work.</p><p>A controller can thus be thought of as a middleman between models and views. It makes the model data available to the view so it can display that data to the user, and it saves or updates user data to the model.</p><div class="note"><p>For more details on the routing process, see <a href="routing.html">Rails Routing from the Outside In</a>.</p></div><h3 id="controller-naming-convention"><a class="anchorlink" href="#controller-naming-convention">2 Controller Naming Convention</a></h3><p>The naming convention of controllers in Rails favors pluralization of the last word in the controller's name, although it is not strictly required (e.g. <code>ApplicationController</code>). For example, <code>ClientsController</code> is preferable to <code>ClientController</code>, <code>SiteAdminsController</code> is preferable to <code>SiteAdminController</code> or <code>SitesAdminsController</code>, and so on.</p><p>Following this convention will allow you to use the default route generators (e.g. <code>resources</code>, etc) without needing to qualify each <code>:path</code> or <code>:controller</code>, and will keep named route helpers' usage consistent throughout your application. See <a href="layouts_and_rendering.html">Layouts & Rendering Guide</a> for more details.</p><div class="note"><p>The controller naming convention differs from the naming convention of models, which are expected to be named in singular form.</p></div><h3 id="methods-and-actions"><a class="anchorlink" href="#methods-and-actions">3 Methods and Actions</a></h3><p>A controller is a Ruby class which inherits from <code>ApplicationController</code> and has methods just like any other class. When your application receives a request, the routing will determine which controller and action to run, then Rails creates an instance of that controller and runs the method with the same name as the action.</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class ClientsController < ApplicationController
def new
end
end
</pre>
</div>
<p>As an example, if a user goes to <code>/clients/new</code> in your application to add a new client, Rails will create an instance of <code>ClientsController</code> and call its <code>new</code> method. Note that the empty method from the example above would work just fine because Rails will by default render the <code>new.html.erb</code> view unless the action says otherwise. By creating a new <code>Client</code>, the <code>new</code> method can make a <code>@client</code> instance variable accessible in the view:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
def new
@client = Client.new
end
</pre>
</div>
<p>The <a href="layouts_and_rendering.html">Layouts & Rendering Guide</a> explains this in more detail.</p><p><code>ApplicationController</code> inherits from <code>ActionController::Base</code>, which defines a number of helpful methods. This guide will cover some of these, but if you're curious to see what's in there, you can see all of them in the <a href="https://api.rubyonrails.org/6-0-stable/classes/ActionController.html">API documentation</a> or in the source itself.</p><p>Only public methods are callable as actions. It is a best practice to lower the visibility of methods (with <code>private</code> or <code>protected</code>) which are not intended to be actions, like auxiliary methods or filters.</p><h3 id="parameters"><a class="anchorlink" href="#parameters">4 Parameters</a></h3><p>You will probably want to access data sent in by the user or other parameters in your controller actions. There are two kinds of parameters possible in a web application. The first are parameters that are sent as part of the URL, called query string parameters. The query string is everything after "?" in the URL. The second type of parameter is usually referred to as POST data. This information usually comes from an HTML form which has been filled in by the user. It's called POST data because it can only be sent as part of an HTTP POST request. Rails does not make any distinction between query string parameters and POST parameters, and both are available in the <code>params</code> hash in your controller:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class ClientsController < ApplicationController
# This action uses query string parameters because it gets run
# by an HTTP GET request, but this does not make any difference
# to the way in which the parameters are accessed. The URL for
# this action would look like this in order to list activated
# clients: /clients?status=activated
def index
if params[:status] == "activated"
@clients = Client.activated
else
@clients = Client.inactivated
end
end
# This action uses POST parameters. They are most likely coming
# from an HTML form which the user has submitted. The URL for
# this RESTful request will be "/clients", and the data will be
# sent as part of the request body.
def create
@client = Client.new(params[:client])
if @client.save
redirect_to @client
else
# This line overrides the default rendering behavior, which
# would have been to render the "create" view.
render "new"
end
end
end
</pre>
</div>
<h4 id="hash-and-array-parameters"><a class="anchorlink" href="#hash-and-array-parameters">4.1 Hash and Array Parameters</a></h4><p>The <code>params</code> hash is not limited to one-dimensional keys and values. It can contain nested arrays and hashes. To send an array of values, append an empty pair of square brackets "[]" to the key name:</p><div class="code_container">
<pre class="brush: plain; gutter: false; toolbar: false">
GET /clients?ids[]=1&ids[]=2&ids[]=3
</pre>
</div>
<div class="note"><p>The actual URL in this example will be encoded as "/clients?ids%5b%5d=1&ids%5b%5d=2&ids%5b%5d=3" as the "[" and "]" characters are not allowed in URLs. Most of the time you don't have to worry about this because the browser will encode it for you, and Rails will decode it automatically, but if you ever find yourself having to send those requests to the server manually you should keep this in mind.</p></div><p>The value of <code>params[:ids]</code> will now be <code>["1", "2", "3"]</code>. Note that parameter values are always strings; Rails makes no attempt to guess or cast the type.</p><div class="note"><p>Values such as <code>[nil]</code> or <code>[nil, nil, ...]</code> in <code>params</code> are replaced
with <code>[]</code> for security reasons by default. See <a href="security.html#unsafe-query-generation">Security Guide</a>
for more information.</p></div><p>To send a hash, you include the key name inside the brackets:</p><div class="code_container">
<pre class="brush: xml; gutter: false; toolbar: false">
<form accept-charset="UTF-8" action="/clients" method="post">
<input type="text" name="client[name]" value="Acme" />
<input type="text" name="client[phone]" value="12345" />
<input type="text" name="client[address][postcode]" value="12345" />
<input type="text" name="client[address][city]" value="Carrot City" />
</form>
</pre>
</div>
<p>When this form is submitted, the value of <code>params[:client]</code> will be <code>{ "name" => "Acme", "phone" => "12345", "address" => { "postcode" => "12345", "city" => "Carrot City" } }</code>. Note the nested hash in <code>params[:client][:address]</code>.</p><p>The <code>params</code> object acts like a Hash, but lets you use symbols and strings interchangeably as keys.</p><h4 id="json-parameters"><a class="anchorlink" href="#json-parameters">4.2 JSON parameters</a></h4><p>If you're writing a web service application, you might find yourself more comfortable accepting parameters in JSON format. If the "Content-Type" header of your request is set to "application/json", Rails will automatically load your parameters into the <code>params</code> hash, which you can access as you would normally.</p><p>So for example, if you are sending this JSON content:</p><div class="code_container">
<pre class="brush: plain; gutter: false; toolbar: false">
{ "company": { "name": "acme", "address": "123 Carrot Street" } }
</pre>
</div>
<p>Your controller will receive <code>params[:company]</code> as <code>{ "name" => "acme", "address" => "123 Carrot Street" }</code>.</p><p>Also, if you've turned on <code>config.wrap_parameters</code> in your initializer or called <code>wrap_parameters</code> in your controller, you can safely omit the root element in the JSON parameter. In this case, the parameters will be cloned and wrapped with a key chosen based on your controller's name. So the above JSON request can be written as:</p><div class="code_container">
<pre class="brush: plain; gutter: false; toolbar: false">
{ "name": "acme", "address": "123 Carrot Street" }
</pre>
</div>
<p>And, assuming that you're sending the data to <code>CompaniesController</code>, it would then be wrapped within the <code>:company</code> key like this:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
{ name: "acme", address: "123 Carrot Street", company: { name: "acme", address: "123 Carrot Street" } }
</pre>
</div>
<p>You can customize the name of the key or specific parameters you want to wrap by consulting the <a href="https://api.rubyonrails.org/6-0-stable/classes/ActionController/ParamsWrapper.html">API documentation</a></p><div class="note"><p>Support for parsing XML parameters has been extracted into a gem named <code>actionpack-xml_parser</code>.</p></div><h4 id="routing-parameters"><a class="anchorlink" href="#routing-parameters">4.3 Routing Parameters</a></h4><p>The <code>params</code> hash will always contain the <code>:controller</code> and <code>:action</code> keys, but you should use the methods <code>controller_name</code> and <code>action_name</code> instead to access these values. Any other parameters defined by the routing, such as <code>:id</code>, will also be available. As an example, consider a listing of clients where the list can show either active or inactive clients. We can add a route which captures the <code>:status</code> parameter in a "pretty" URL:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
get '/clients/:status', to: 'clients#index', foo: 'bar'
</pre>
</div>
<p>In this case, when a user opens the URL <code>/clients/active</code>, <code>params[:status]</code> will be set to "active". When this route is used, <code>params[:foo]</code> will also be set to "bar", as if it were passed in the query string. Your controller will also receive <code>params[:action]</code> as "index" and <code>params[:controller]</code> as "clients".</p><h4 id="default-url-options"><a class="anchorlink" href="#default-url-options">4.4 <code>default_url_options</code></a></h4><p>You can set global default parameters for URL generation by defining a method called <code>default_url_options</code> in your controller. Such a method must return a hash with the desired defaults, whose keys must be symbols:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class ApplicationController < ActionController::Base
def default_url_options
{ locale: I18n.locale }
end
end
</pre>
</div>
<p>These options will be used as a starting point when generating URLs, so it's possible they'll be overridden by the options passed to <code>url_for</code> calls.</p><p>If you define <code>default_url_options</code> in <code>ApplicationController</code>, as in the example above, these defaults will be used for all URL generation. The method can also be defined in a specific controller, in which case it only affects URLs generated there.</p><p>In a given request, the method is not actually called for every single generated URL; for performance reasons, the returned hash is cached, there is at most one invocation per request.</p><h4 id="strong-parameters"><a class="anchorlink" href="#strong-parameters">4.5 Strong Parameters</a></h4><p>With strong parameters, Action Controller parameters are forbidden to
be used in Active Model mass assignments until they have been
permitted. This means that you'll have to make a conscious decision about
which attributes to permit for mass update. This is a better security
practice to help prevent accidentally allowing users to update sensitive
model attributes.</p><p>In addition, parameters can be marked as required and will flow through a
predefined raise/rescue flow that will result in a 400 Bad Request being
returned if not all required parameters are passed in.</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class PeopleController < ActionController::Base
# This will raise an ActiveModel::ForbiddenAttributesError exception
# because it's using mass assignment without an explicit permit
# step.
def create
Person.create(params[:person])
end
# This will pass with flying colors as long as there's a person key
# in the parameters, otherwise it'll raise an
# ActionController::ParameterMissing exception, which will get
# caught by ActionController::Base and turned into a 400 Bad
# Request error.
def update
person = current_account.people.find(params[:id])
person.update!(person_params)
redirect_to person
end
private
# Using a private method to encapsulate the permissible parameters
# is just a good pattern since you'll be able to reuse the same
# permit list between create and update. Also, you can specialize
# this method with per-user checking of permissible attributes.
def person_params
params.require(:person).permit(:name, :age)
end
end
</pre>
</div>
<h5 id="permitted-scalar-values"><a class="anchorlink" href="#permitted-scalar-values">4.5.1 Permitted Scalar Values</a></h5><p>Given</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
params.permit(:id)
</pre>
</div>
<p>the key <code>:id</code> will be permitted for inclusion if it appears in <code>params</code> and
it has a permitted scalar value associated. Otherwise, the key is going
to be filtered out, so arrays, hashes, or any other objects cannot be
injected.</p><p>The permitted scalar types are <code>String</code>, <code>Symbol</code>, <code>NilClass</code>,
<code>Numeric</code>, <code>TrueClass</code>, <code>FalseClass</code>, <code>Date</code>, <code>Time</code>, <code>DateTime</code>,
<code>StringIO</code>, <code>IO</code>, <code>ActionDispatch::Http::UploadedFile</code>, and
<code>Rack::Test::UploadedFile</code>.</p><p>To declare that the value in <code>params</code> must be an array of permitted
scalar values, map the key to an empty array:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
params.permit(id: [])
</pre>
</div>
<p>Sometimes it is not possible or convenient to declare the valid keys of
a hash parameter or its internal structure. Just map to an empty hash:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
params.permit(preferences: {})
</pre>
</div>
<p>but be careful because this opens the door to arbitrary input. In this
case, <code>permit</code> ensures values in the returned structure are permitted
scalars and filters out anything else.</p><p>To permit an entire hash of parameters, the <code>permit!</code> method can be
used:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
params.require(:log_entry).permit!
</pre>
</div>
<p>This marks the <code>:log_entry</code> parameters hash and any sub-hash of it as
permitted and does not check for permitted scalars, anything is accepted.
Extreme care should be taken when using <code>permit!</code>, as it will allow all current
and future model attributes to be mass-assigned.</p><h5 id="nested-parameters"><a class="anchorlink" href="#nested-parameters">4.5.2 Nested Parameters</a></h5><p>You can also use <code>permit</code> on nested parameters, like:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
params.permit(:name, { emails: [] },
friends: [ :name,
{ family: [ :name ], hobbies: [] }])
</pre>
</div>
<p>This declaration permits the <code>name</code>, <code>emails</code>, and <code>friends</code>
attributes. It is expected that <code>emails</code> will be an array of permitted
scalar values, and that <code>friends</code> will be an array of resources with
specific attributes: they should have a <code>name</code> attribute (any
permitted scalar values allowed), a <code>hobbies</code> attribute as an array of
permitted scalar values, and a <code>family</code> attribute which is restricted
to having a <code>name</code> (any permitted scalar values allowed here, too).</p><h5 id="more-examples"><a class="anchorlink" href="#more-examples">4.5.3 More Examples</a></h5><p>You may want to also use the permitted attributes in your <code>new</code>
action. This raises the problem that you can't use <code>require</code> on the
root key because, normally, it does not exist when calling <code>new</code>:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
# using `fetch` you can supply a default and use
# the Strong Parameters API from there.
params.fetch(:blog, {}).permit(:title, :author)
</pre>
</div>
<p>The model class method <code>accepts_nested_attributes_for</code> allows you to
update and destroy associated records. This is based on the <code>id</code> and <code>_destroy</code>
parameters:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
# permit :id and :_destroy
params.require(:author).permit(:name, books_attributes: [:title, :id, :_destroy])
</pre>
</div>
<p>Hashes with integer keys are treated differently, and you can declare
the attributes as if they were direct children. You get these kinds of
parameters when you use <code>accepts_nested_attributes_for</code> in combination
with a <code>has_many</code> association:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
# To permit the following data:
# {"book" => {"title" => "Some Book",
# "chapters_attributes" => { "1" => {"title" => "First Chapter"},
# "2" => {"title" => "Second Chapter"}}}}
params.require(:book).permit(:title, chapters_attributes: [:title])
</pre>
</div>
<p>Imagine a scenario where you have parameters representing a product
name and a hash of arbitrary data associated with that product, and
you want to permit the product name attribute and also the whole
data hash:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
def product_params
params.require(:product).permit(:name, data: {})
end
</pre>
</div>
<h5 id="outside-the-scope-of-strong-parameters"><a class="anchorlink" href="#outside-the-scope-of-strong-parameters">4.5.4 Outside the Scope of Strong Parameters</a></h5><p>The strong parameter API was designed with the most common use cases
in mind. It is not meant as a silver bullet to handle all of your
parameter filtering problems. However, you can easily mix the API with your
own code to adapt to your situation.</p><h3 id="session"><a class="anchorlink" href="#session">5 Session</a></h3><p>Your application has a session for each user in which you can store small amounts of data that will be persisted between requests. The session is only available in the controller and the view and can use one of a number of different storage mechanisms:</p>
<ul>
<li>
<code>ActionDispatch::Session::CookieStore</code> - Stores everything on the client.</li>
<li>
<code>ActionDispatch::Session::CacheStore</code> - Stores the data in the Rails cache.</li>
<li>
<code>ActionDispatch::Session::ActiveRecordStore</code> - Stores the data in a database using Active Record. (require <code>activerecord-session_store</code> gem).</li>
<li>
<code>ActionDispatch::Session::MemCacheStore</code> - Stores the data in a memcached cluster (this is a legacy implementation; consider using CacheStore instead).</li>
</ul>
<p>All session stores use a cookie to store a unique ID for each session (you must use a cookie, Rails will not allow you to pass the session ID in the URL as this is less secure).</p><p>For most stores, this ID is used to look up the session data on the server, e.g. in a database table. There is one exception, and that is the default and recommended session store - the CookieStore - which stores all session data in the cookie itself (the ID is still available to you if you need it). This has the advantage of being very lightweight and it requires zero setup in a new application in order to use the session. The cookie data is cryptographically signed to make it tamper-proof. And it is also encrypted so anyone with access to it can't read its contents. (Rails will not accept it if it has been edited).</p><p>The CookieStore can store around 4kB of data - much less than the others - but this is usually enough. Storing large amounts of data in the session is discouraged no matter which session store your application uses. You should especially avoid storing complex objects (anything other than basic Ruby objects, the most common example being model instances) in the session, as the server might not be able to reassemble them between requests, which will result in an error.</p><p>If your user sessions don't store critical data or don't need to be around for long periods (for instance if you just use the flash for messaging), you can consider using <code>ActionDispatch::Session::CacheStore</code>. This will store sessions using the cache implementation you have configured for your application. The advantage of this is that you can use your existing cache infrastructure for storing sessions without requiring any additional setup or administration. The downside, of course, is that the sessions will be ephemeral and could disappear at any time.</p><p>Read more about session storage in the <a href="security.html">Security Guide</a>.</p><p>If you need a different session storage mechanism, you can change it in an initializer:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
# Use the database for sessions instead of the cookie-based default,
# which shouldn't be used to store highly confidential information
# (create the session table with "rails g active_record:session_migration")
# Rails.application.config.session_store :active_record_store
</pre>
</div>
<p>Rails sets up a session key (the name of the cookie) when signing the session data. These can also be changed in an initializer:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
# Be sure to restart your server when you modify this file.
Rails.application.config.session_store :cookie_store, key: '_your_app_session'
</pre>
</div>
<p>You can also pass a <code>:domain</code> key and specify the domain name for the cookie:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
# Be sure to restart your server when you modify this file.
Rails.application.config.session_store :cookie_store, key: '_your_app_session', domain: ".example.com"
</pre>
</div>
<p>Rails sets up (for the CookieStore) a secret key used for signing the session data in <code>config/credentials.yml.enc</code>. This can be changed with <code>rails credentials:edit</code>.</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
# aws:
# access_key_id: 123
# secret_access_key: 345
# Used as the base secret for all MessageVerifiers in Rails, including the one protecting cookies.
secret_key_base: 492f...
</pre>
</div>
<div class="note"><p>Changing the secret_key_base when using the <code>CookieStore</code> will invalidate all existing sessions.</p></div><h4 id="accessing-the-session"><a class="anchorlink" href="#accessing-the-session">5.1 Accessing the Session</a></h4><p>In your controller you can access the session through the <code>session</code> instance method.</p><div class="note"><p>Sessions are lazily loaded. If you don't access sessions in your action's code, they will not be loaded. Hence you will never need to disable sessions, just not accessing them will do the job.</p></div><p>Session values are stored using key/value pairs like a hash:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class ApplicationController < ActionController::Base
private
# Finds the User with the ID stored in the session with the key
# :current_user_id This is a common way to handle user login in
# a Rails application; logging in sets the session value and
# logging out removes it.
def current_user
@_current_user ||= session[:current_user_id] &&
User.find_by(id: session[:current_user_id])
end
end
</pre>
</div>
<p>To store something in the session, just assign it to the key like a hash:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class LoginsController < ApplicationController
# "Create" a login, aka "log the user in"
def create
if user = User.authenticate(params[:username], params[:password])
# Save the user ID in the session so it can be used in
# subsequent requests
session[:current_user_id] = user.id
redirect_to root_url
end
end
end
</pre>
</div>
<p>To remove something from the session, delete the key/value pair:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class LoginsController < ApplicationController
# "Delete" a login, aka "log the user out"
def destroy
# Remove the user id from the session
session.delete(:current_user_id)
# Clear the memoized current user
@_current_user = nil
redirect_to root_url
end
end
</pre>
</div>
<p>To reset the entire session, use <code>reset_session</code>.</p><h4 id="the-flash"><a class="anchorlink" href="#the-flash">5.2 The Flash</a></h4><p>The flash is a special part of the session which is cleared with each request. This means that values stored there will only be available in the next request, which is useful for passing error messages etc.</p><p>It is accessed in much the same way as the session, as a hash (it's a <a href="https://api.rubyonrails.org/6-0-stable/classes/ActionDispatch/Flash/FlashHash.html">FlashHash</a> instance).</p><p>Let's use the act of logging out as an example. The controller can send a message which will be displayed to the user on the next request:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class LoginsController < ApplicationController
def destroy
session.delete(:current_user_id)
flash[:notice] = "You have successfully logged out."
redirect_to root_url
end
end
</pre>
</div>
<p>Note that it is also possible to assign a flash message as part of the redirection. You can assign <code>:notice</code>, <code>:alert</code> or the general purpose <code>:flash</code>:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
redirect_to root_url, notice: "You have successfully logged out."
redirect_to root_url, alert: "You're stuck here!"
redirect_to root_url, flash: { referral_code: 1234 }
</pre>
</div>
<p>The <code>destroy</code> action redirects to the application's <code>root_url</code>, where the message will be displayed. Note that it's entirely up to the next action to decide what, if anything, it will do with what the previous action put in the flash. It's conventional to display any error alerts or notices from the flash in the application's layout:</p><div class="code_container">
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
<html>
<!-- <head/> -->
<body>
<% flash.each do |name, msg| -%>
<%= content_tag :div, msg, class: name %>
<% end -%>
<!-- more content -->
</body>
</html>
</pre>
</div>
<p>This way, if an action sets a notice or an alert message, the layout will display it automatically.</p><p>You can pass anything that the session can store; you're not limited to notices and alerts:</p><div class="code_container">
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
<% if flash[:just_signed_up] %>
<p class="welcome">Welcome to our site!</p>
<% end %>
</pre>
</div>
<p>If you want a flash value to be carried over to another request, use the <code>keep</code> method:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class MainController < ApplicationController
# Let's say this action corresponds to root_url, but you want
# all requests here to be redirected to UsersController#index.
# If an action sets the flash and redirects here, the values
# would normally be lost when another redirect happens, but you
# can use 'keep' to make it persist for another request.
def index
# Will persist all flash values.
flash.keep
# You can also use a key to keep only some kind of value.
# flash.keep(:notice)
redirect_to users_url
end
end
</pre>
</div>
<h5 id="flash-now"><a class="anchorlink" href="#flash-now">5.2.1 <code>flash.now</code></a></h5><p>By default, adding values to the flash will make them available to the next request, but sometimes you may want to access those values in the same request. For example, if the <code>create</code> action fails to save a resource and you render the <code>new</code> template directly, that's not going to result in a new request, but you may still want to display a message using the flash. To do this, you can use <code>flash.now</code> in the same way you use the normal <code>flash</code>:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class ClientsController < ApplicationController
def create
@client = Client.new(params[:client])
if @client.save
# ...
else
flash.now[:error] = "Could not save client"
render action: "new"
end
end
end
</pre>
</div>
<h3 id="cookies"><a class="anchorlink" href="#cookies">6 Cookies</a></h3><p>Your application can store small amounts of data on the client - called cookies - that will be persisted across requests and even sessions. Rails provides easy access to cookies via the <code>cookies</code> method, which - much like the <code>session</code> - works like a hash:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class CommentsController < ApplicationController
def new
# Auto-fill the commenter's name if it has been stored in a cookie
@comment = Comment.new(author: cookies[:commenter_name])
end
def create
@comment = Comment.new(params[:comment])
if @comment.save
flash[:notice] = "Thanks for your comment!"
if params[:remember_name]
# Remember the commenter's name.
cookies[:commenter_name] = @comment.author
else
# Delete cookie for the commenter's name cookie, if any.
cookies.delete(:commenter_name)
end
redirect_to @comment.article
else
render action: "new"
end
end
end
</pre>
</div>
<p>Note that while for session values you set the key to <code>nil</code>, to delete a cookie value you should use <code>cookies.delete(:key)</code>.</p><p>Rails also provides a signed cookie jar and an encrypted cookie jar for storing
sensitive data. The signed cookie jar appends a cryptographic signature on the
cookie values to protect their integrity. The encrypted cookie jar encrypts the
values in addition to signing them, so that they cannot be read by the end user.
Refer to the <a href="https://api.rubyonrails.org/6-0-stable/classes/ActionDispatch/Cookies.html">API documentation</a>
for more details.</p><p>These special cookie jars use a serializer to serialize the assigned values into
strings and deserializes them into Ruby objects on read.</p><p>You can specify what serializer to use:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
Rails.application.config.action_dispatch.cookies_serializer = :json
</pre>
</div>
<p>The default serializer for new applications is <code>:json</code>. For compatibility with
old applications with existing cookies, <code>:marshal</code> is used when <code>serializer</code>
option is not specified.</p><p>You may also set this option to <code>:hybrid</code>, in which case Rails would transparently
deserialize existing (<code>Marshal</code>-serialized) cookies on read and re-write them in
the <code>JSON</code> format. This is useful for migrating existing applications to the
<code>:json</code> serializer.</p><p>It is also possible to pass a custom serializer that responds to <code>load</code> and
<code>dump</code>:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
Rails.application.config.action_dispatch.cookies_serializer = MyCustomSerializer
</pre>
</div>
<p>When using the <code>:json</code> or <code>:hybrid</code> serializer, you should beware that not all
Ruby objects can be serialized as JSON. For example, <code>Date</code> and <code>Time</code> objects
will be serialized as strings, and <code>Hash</code>es will have their keys stringified.</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class CookiesController < ApplicationController
def set_cookie
cookies.encrypted[:expiration_date] = Date.tomorrow # => Thu, 20 Mar 2014
redirect_to action: 'read_cookie'
end
def read_cookie
cookies.encrypted[:expiration_date] # => "2014-03-20"
end
end
</pre>
</div>
<p>It's advisable that you only store simple data (strings and numbers) in cookies.
If you have to store complex objects, you would need to handle the conversion
manually when reading the values on subsequent requests.</p><p>If you use the cookie session store, this would apply to the <code>session</code> and
<code>flash</code> hash as well.</p><h3 id="rendering-xml-and-json-data"><a class="anchorlink" href="#rendering-xml-and-json-data">7 Rendering XML and JSON data</a></h3><p>ActionController makes it extremely easy to render <code>XML</code> or <code>JSON</code> data. If you've generated a controller using scaffolding, it would look something like this:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class UsersController < ApplicationController
def index
@users = User.all
respond_to do |format|
format.html # index.html.erb
format.xml { render xml: @users }
format.json { render json: @users }
end
end
end
</pre>
</div>
<p>You may notice in the above code that we're using <code>render xml: @users</code>, not <code>render xml: @users.to_xml</code>. If the object is not a String, then Rails will automatically invoke <code>to_xml</code> for us.</p><h3 id="filters"><a class="anchorlink" href="#filters">8 Filters</a></h3><p>Filters are methods that are run "before", "after" or "around" a controller action.</p><p>Filters are inherited, so if you set a filter on <code>ApplicationController</code>, it will be run on every controller in your application.</p><p>"before" filters may halt the request cycle. A common "before" filter is one which requires that a user is logged in for an action to be run. You can define the filter method this way:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class ApplicationController < ActionController::Base
before_action :require_login
private
def require_login
unless logged_in?
flash[:error] = "You must be logged in to access this section"
redirect_to new_login_url # halts request cycle
end
end
end
</pre>
</div>
<p>The method simply stores an error message in the flash and redirects to the login form if the user is not logged in. If a "before" filter renders or redirects, the action will not run. If there are additional filters scheduled to run after that filter, they are also cancelled.</p><p>In this example the filter is added to <code>ApplicationController</code> and thus all controllers in the application inherit it. This will make everything in the application require the user to be logged in in order to use it. For obvious reasons (the user wouldn't be able to log in in the first place!), not all controllers or actions should require this. You can prevent this filter from running before particular actions with <code>skip_before_action</code>:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class LoginsController < ApplicationController
skip_before_action :require_login, only: [:new, :create]
end
</pre>
</div>
<p>Now, the <code>LoginsController</code>'s <code>new</code> and <code>create</code> actions will work as before without requiring the user to be logged in. The <code>:only</code> option is used to skip this filter only for these actions, and there is also an <code>:except</code> option which works the other way. These options can be used when adding filters too, so you can add a filter which only runs for selected actions in the first place.</p><div class="note"><p>Calling the same filter multiple times with different options will not work,
since the last filter definition will overwrite the previous ones.</p></div><h4 id="after-filters-and-around-filters"><a class="anchorlink" href="#after-filters-and-around-filters">8.1 After Filters and Around Filters</a></h4><p>In addition to "before" filters, you can also run filters after an action has been executed, or both before and after.</p><p>"after" filters are similar to "before" filters, but because the action has already been run they have access to the response data that's about to be sent to the client. Obviously, "after" filters cannot stop the action from running. Please note that "after" filters are executed only after a successful action, but not when an exception is raised in the request cycle.</p><p>"around" filters are responsible for running their associated actions by yielding, similar to how Rack middlewares work.</p><p>For example, in a website where changes have an approval workflow an administrator could be able to preview them easily, just apply them within a transaction:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class ChangesController < ApplicationController
around_action :wrap_in_transaction, only: :show
private
def wrap_in_transaction
ActiveRecord::Base.transaction do
begin
yield
ensure
raise ActiveRecord::Rollback
end
end
end
end
</pre>
</div>
<p>Note that an "around" filter also wraps rendering. In particular, if in the example above, the view itself reads from the database (e.g. via a scope), it will do so within the transaction and thus present the data to preview.</p><p>You can choose not to yield and build the response yourself, in which case the action will not be run.</p><h4 id="other-ways-to-use-filters"><a class="anchorlink" href="#other-ways-to-use-filters">8.2 Other Ways to Use Filters</a></h4><p>While the most common way to use filters is by creating private methods and using *_action to add them, there are two other ways to do the same thing.</p><p>The first is to use a block directly with the *_action methods. The block receives the controller as an argument. The <code>require_login</code> filter from above could be rewritten to use a block:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class ApplicationController < ActionController::Base
before_action do |controller|
unless controller.send(:logged_in?)
flash[:error] = "You must be logged in to access this section"
redirect_to new_login_url
end
end
end
</pre>
</div>
<p>Note that the filter in this case uses <code>send</code> because the <code>logged_in?</code> method is private and the filter does not run in the scope of the controller. This is not the recommended way to implement this particular filter, but in more simple cases it might be useful.</p><p>The second way is to use a class (actually, any object that responds to the right methods will do) to handle the filtering. This is useful in cases that are more complex and cannot be implemented in a readable and reusable way using the two other methods. As an example, you could rewrite the login filter again to use a class:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class ApplicationController < ActionController::Base
before_action LoginFilter
end
class LoginFilter
def self.before(controller)
unless controller.send(:logged_in?)
controller.flash[:error] = "You must be logged in to access this section"
controller.redirect_to controller.new_login_url
end
end
end
</pre>
</div>
<p>Again, this is not an ideal example for this filter, because it's not run in the scope of the controller but gets the controller passed as an argument. The filter class must implement a method with the same name as the filter, so for the <code>before_action</code> filter the class must implement a <code>before</code> method, and so on. The <code>around</code> method must <code>yield</code> to execute the action.</p><h3 id="request-forgery-protection"><a class="anchorlink" href="#request-forgery-protection">9 Request Forgery Protection</a></h3><p>Cross-site request forgery is a type of attack in which a site tricks a user into making requests on another site, possibly adding, modifying, or deleting data on that site without the user's knowledge or permission.</p><p>The first step to avoid this is to make sure all "destructive" actions (create, update, and destroy) can only be accessed with non-GET requests. If you're following RESTful conventions you're already doing this. However, a malicious site can still send a non-GET request to your site quite easily, and that's where the request forgery protection comes in. As the name says, it protects from forged requests.</p><p>The way this is done is to add a non-guessable token which is only known to your server to each request. This way, if a request comes in without the proper token, it will be denied access.</p><p>If you generate a form like this:</p><div class="code_container">
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
<%= form_with model: @user, local: true do |form| %>
<%= form.text_field :username %>
<%= form.text_field :password %>
<% end %>
</pre>
</div>
<p>You will see how the token gets added as a hidden field:</p><div class="code_container">
<pre class="brush: xml; gutter: false; toolbar: false">
<form accept-charset="UTF-8" action="/users/1" method="post">
<input type="hidden"
value="67250ab105eb5ad10851c00a5621854a23af5489"
name="authenticity_token"/>
<!-- fields -->
</form>
</pre>
</div>
<p>Rails adds this token to every form that's generated using the <a href="form_helpers.html">form helpers</a>, so most of the time you don't have to worry about it. If you're writing a form manually or need to add the token for another reason, it's available through the method <code>form_authenticity_token</code>:</p><p>The <code>form_authenticity_token</code> generates a valid authentication token. That's useful in places where Rails does not add it automatically, like in custom Ajax calls.</p><p>The <a href="security.html">Security Guide</a> has more about this and a lot of other security-related issues that you should be aware of when developing a web application.</p><h3 id="the-request-and-response-objects"><a class="anchorlink" href="#the-request-and-response-objects">10 The Request and Response Objects</a></h3><p>In every controller there are two accessor methods pointing to the request and the response objects associated with the request cycle that is currently in execution. The <code>request</code> method contains an instance of <code>ActionDispatch::Request</code> and the <code>response</code> method returns a response object representing what is going to be sent back to the client.</p><h4 id="the-request-object"><a class="anchorlink" href="#the-request-object">10.1 The <code>request</code> Object</a></h4><p>The request object contains a lot of useful information about the request coming in from the client. To get a full list of the available methods, refer to the <a href="https://api.rubyonrails.org/6-0-stable/classes/ActionDispatch/Request.html">Rails API documentation</a> and <a href="https://www.rubydoc.info/github/rack/rack/Rack/Request">Rack Documentation</a>. Among the properties that you can access on this object are:</p>
<table>
<thead>
<tr>
<th>Property of <code>request</code>
</th>
<th>Purpose</th>
</tr>
</thead>
<tbody>
<tr>
<td>host</td>
<td>The hostname used for this request.</td>
</tr>
<tr>
<td>domain(n=2)</td>
<td>The hostname's first <code>n</code> segments, starting from the right (the TLD).</td>
</tr>
<tr>
<td>format</td>
<td>The content type requested by the client.</td>
</tr>
<tr>
<td>method</td>
<td>The HTTP method used for the request.</td>
</tr>
<tr>
<td>get?, post?, patch?, put?, delete?, head?</td>
<td>Returns true if the HTTP method is GET/POST/PATCH/PUT/DELETE/HEAD.</td>
</tr>
<tr>
<td>headers</td>
<td>Returns a hash containing the headers associated with the request.</td>
</tr>
<tr>
<td>port</td>
<td>The port number (integer) used for the request.</td>
</tr>
<tr>
<td>protocol</td>
<td>Returns a string containing the protocol used plus "://", for example "http://".</td>
</tr>
<tr>
<td>query_string</td>
<td>The query string part of the URL, i.e., everything after "?".</td>
</tr>
<tr>
<td>remote_ip</td>
<td>The IP address of the client.</td>
</tr>
<tr>
<td>url</td>
<td>The entire URL used for the request.</td>
</tr>
</tbody>
</table>
<h5 id="path-parameters-query-parameters-and-request-parameters"><a class="anchorlink" href="#path-parameters-query-parameters-and-request-parameters">10.1.1 <code>path_parameters</code>, <code>query_parameters</code>, and <code>request_parameters</code></a></h5><p>Rails collects all of the parameters sent along with the request in the <code>params</code> hash, whether they are sent as part of the query string or the post body. The request object has three accessors that give you access to these parameters depending on where they came from. The <code>query_parameters</code> hash contains parameters that were sent as part of the query string while the <code>request_parameters</code> hash contains parameters sent as part of the post body. The <code>path_parameters</code> hash contains parameters that were recognized by the routing as being part of the path leading to this particular controller and action.</p><h4 id="the-response-object"><a class="anchorlink" href="#the-response-object">10.2 The <code>response</code> Object</a></h4><p>The response object is not usually used directly, but is built up during the execution of the action and rendering of the data that is being sent back to the user, but sometimes - like in an after filter - it can be useful to access the response directly. Some of these accessor methods also have setters, allowing you to change their values. To get a full list of the available methods, refer to the <a href="https://api.rubyonrails.org/6-0-stable/classes/ActionDispatch/Response.html">Rails API documentation</a> and <a href="https://www.rubydoc.info/github/rack/rack/Rack/Response">Rack Documentation</a>.</p>
<table>
<thead>
<tr>
<th>Property of <code>response</code>
</th>
<th>Purpose</th>
</tr>
</thead>
<tbody>
<tr>
<td>body</td>
<td>This is the string of data being sent back to the client. This is most often HTML.</td>
</tr>
<tr>
<td>status</td>
<td>The HTTP status code for the response, like 200 for a successful request or 404 for file not found.</td>
</tr>
<tr>
<td>location</td>
<td>The URL the client is being redirected to, if any.</td>
</tr>
<tr>
<td>content_type</td>
<td>The content type of the response.</td>
</tr>
<tr>
<td>charset</td>
<td>The character set being used for the response. Default is "utf-8".</td>
</tr>
<tr>
<td>headers</td>
<td>Headers used for the response.</td>
</tr>