This repository has been archived by the owner on Jan 7, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
form_helpers.html
1022 lines (938 loc) · 69.1 KB
/
form_helpers.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 PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>Ruby on Rails Guides: Rails Form helpers</title>
<link rel="stylesheet" type="text/css" href="stylesheets/style.css" />
<link rel="stylesheet" type="text/css" href="stylesheets/print.css" media="print" />
<link rel="stylesheet" type="text/css" href="stylesheets/syntaxhighlighter/shCore.css" />
<link rel="stylesheet" type="text/css" href="stylesheets/syntaxhighlighter/shThemeRailsGuides.css" />
</head>
<body class="guide">
<div id="topNav">
<div class="wrapper">
<strong>More at <a href="http://rubyonrails.org/">rubyonrails.org:</a> </strong>
<a href="http://rubyonrails.org/">Overview</a> |
<a href="http://rubyonrails.org/download">Download</a> |
<a href="http://rubyonrails.org/deploy">Deploy</a> |
<a href="http://rails.lighthouseapp.com/projects/8994-ruby-on-rails/overview">Code</a> |
<a href="http://rubyonrails.org/screencasts">Screencasts</a> |
<a href="http://rubyonrails.org/documentation">Documentation</a> |
<a href="http://rubyonrails.org/ecosystem">Ecosystem</a> |
<a href="http://rubyonrails.org/community">Community</a> |
<a href="http://weblog.rubyonrails.org/">Blog</a>
</div>
</div>
<div id="header">
<div class="wrapper clearfix">
<h1><a href="index.html" title="Return to home page">Guides.rubyonrails.org</a></h1>
<p class="hide"><a href="#mainCol">Skip navigation</a>.</p>
<ul class="nav">
<li><a href="index.html">홈</a></li>
<li class="index"><a href="index.html" onclick="guideMenu(); return false;" id="guidesMenu">목차</a>
<div id="guides" class="clearfix" style="display: none;">
<hr />
<dl class="L">
<dt>시작</dt>
<dd><a href="getting_started.html">레일즈 시작하기</a></dd>
<dt>모델(Models)</dt>
<dd><a href="migrations.html">레일즈 데이터베이스 마이그레이션</a></dd>
<dd><a href="active_record_validations_callbacks.html">액티브 레코드 데이터 검증(Validation)과 Callback(콜백)</a></dd>
<dd><a href="association_basics.html">액티브 레코드 Association(관계)</a></dd>
<dd><a href="active_record_querying.html">액티브 레코드 쿼리 인터페이스</a></dd>
<dt>뷰(Views)</dt>
<dd><a href="layouts_and_rendering.html">레이아웃(Layouts)과 렌더링(Rendering)</a></dd>
<dd><a href="form_helpers.html">액션 뷰 폼 핼퍼(Action View Form Helpers)</a></dd>
<dt>컨트롤러(Controllers)</dt>
<dd><a href="action_controller_overview.html">액션 컨트롤러 둘러보기</a></dd>
<dd><a href="routing.html">외부 요청에 대한 레일즈 라우팅</a></dd>
</dl>
<dl class="R">
<dt>심화내용</dt>
<dd><a href="active_support_core_extensions.html">액티브 서포트(Active Support) 확장(Core Extensions)</a></dd>
<dd><a href="i18n.html">레일즈 국제화I(nternationalization) API</a></dd>
<dd><a href="action_mailer_basics.html">액션 메일러의 기본</a></dd>
<dd><a href="testing.html">레일즈 어플리케이션 테스트하기</a></dd>
<dd><a href="security.html">레일즈 어플리케이션의 보안</a></dd>
<dd><a href="debugging_rails_applications.html">레일즈 어플리케이션 디버깅</a></dd>
<dd><a href="performance_testing.html">레일즈 어플리케이션 성능 테스트하기</a></dd>
<dd><a href="configuring.html">레일즈 어플리케이션 설정</a></dd>
<dd><a href="command_line.html">레일즈 커멘드라인 도구와 Rake 테스크</a></dd>
<dd><a href="caching_with_rails.html">레일즈를 이용한 캐싱</a></dd>
<dt>레일즈 확장하기(Extending Rails)</dt>
<dd><a href="plugins.html">레일즈 플러그인 작성의 기본</a></dd>
<dd><a href="rails_on_rack.html">렉 위의 레일즈(Rails on Rack)</a></dd>
<dd><a href="generators.html">레일즈 제너레이터(Generator) 제작과 수정</a></dd>
<dt>루비 온 레이즈에 기여하기</dt>
<dd><a href="contributing_to_ruby_on_rails.html">루비 온 레이즈에 기여하기</a></dd>
<dd><a href="api_documentation_guidelines.html">API 문서 가이드라인</a></dd>
<dd><a href="ruby_on_rails_guides_guidelines.html">루비 온 레일즈 가이드에 대한 가이드라인</a></dd>
<dt>Release Notes</dt>
<dd><a href="3_0_release_notes.html">Ruby on Rails 3.0 Release Notes</a></dd>
<dd><a href="2_3_release_notes.html">Ruby on Rails 2.3 Release Notes</a></dd>
<dd><a href="2_2_release_notes.html">Ruby on Rails 2.2 Release Notes</a></dd>
</dl>
</div>
</li>
<li><a href="contribute.html">기여하기</a></li>
<li><a href="credits.html">수고하신 분들</a></li>
</ul>
</div>
</div>
<hr class="hide" />
<div id="feature">
<div class="wrapper">
<h2>Rails Form helpers</h2>
<p>Forms in web applications are an essential interface for user input. However, form markup can quickly become tedious to write and maintain because of form control naming and their numerous attributes. Rails deals away with these complexities by providing view helpers for generating form markup. However, since they have different use-cases, developers are required to know all the differences between similar helper methods before putting them to use.</p>
<p>In this guide you will:</p>
<ul>
<li>Create search forms and similar kind of generic forms not representing any specific model in your application</li>
<li>Make model-centric forms for creation and editing of specific database records</li>
<li>Generate select boxes from multiple types of data</li>
<li>Understand the date and time helpers Rails provides</li>
<li>Learn what makes a file upload form different</li>
<li>Find out where to look for complex forms</li>
</ul>
<div id="subCol">
<h3 class="chapter"><img src="images/chapters_icon.gif" alt="" />Chapters</h3>
<ol class="chapters">
<li><a href="#dealing-with-basic-forms">Dealing with Basic Forms</a><ul><li><a href="#a-generic-search-form">A Generic Search Form</a></li> <li><a href="#multiple-hashes-in-form-helper-calls">Multiple Hashes in Form Helper Calls</a></li> <li><a href="#helpers-for-generating-form-elements">Helpers for Generating Form Elements</a></li> <li><a href="#other-helpers-of-interest">Other Helpers of Interest</a></li></ul></li><li><a href="#dealing-with-model-objects">Dealing with Model Objects</a><ul><li><a href="#model-object-helpers">Model Object Helpers</a></li> <li><a href="#binding-a-form-to-an-object">Binding a Form to an Object</a></li> <li><a href="#relying-on-record-identification">Relying on Record Identification</a></li> <li><a href="#how-do-forms-with-put-or-delete-methods-work">How do forms with <span class="caps">PUT</span> or <span class="caps">DELETE</span> methods work?</a></li></ul></li><li><a href="#making-select-boxes-with-ease">Making Select Boxes with Ease</a><ul><li><a href="#the-select-and-option-tags">The Select and Option Tags</a></li> <li><a href="#select-boxes-for-dealing-with-models">Select Boxes for Dealing with Models</a></li> <li><a href="#option-tags-from-a-collection-of-arbitrary-objects">Option Tags from a Collection of Arbitrary Objects</a></li> <li><a href="#time-zone-and-country-select">Time Zone and Country Select</a></li></ul></li><li><a href="#using-date-and-time-form-helpers">Using Date and Time Form Helpers</a><ul><li><a href="#barebones-helpers">Barebones Helpers</a></li> <li><a href="#select-model-object-helpers">Model Object Helpers</a></li> <li><a href="#common-options">Common Options</a></li> <li><a href="#individual-components">Individual Components</a></li></ul></li><li><a href="#uploading-files">Uploading Files</a><ul><li><a href="#what-gets-uploaded">What Gets Uploaded</a></li> <li><a href="#dealing-with-ajax">Dealing with Ajax</a></li></ul></li><li><a href="#customizing-form-builders">Customizing Form Builders</a></li><li><a href="#understanding-parameter-naming-conventions">Understanding Parameter Naming Conventions</a><ul><li><a href="#basic-structures">Basic Structures</a></li> <li><a href="#combining-them">Combining Them</a></li> <li><a href="#using-form-helpers">Using Form Helpers</a></li></ul></li><li><a href="#building-complex-forms">Building Complex Forms</a></li><li><a href="#changelog">Changelog</a></li><li><a href="#authors">Authors</a></li></ol></div>
</div>
</div>
<div id="container">
<div class="wrapper">
<div id="mainCol">
<div class='note'><p>This guide is not intended to be a complete documentation of available form helpers and their arguments. Please visit <a href="http://api.rubyonrails.org/">the Rails <span class="caps">API</span> documentation</a> for a complete reference.</p></div>
<h3 id="dealing-with-basic-forms">1 Dealing with Basic Forms</h3>
<p>The most basic form helper is <tt>form_tag</tt>.</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
<%= form_tag do %>
Form contents
<% end %>
</pre>
</div>
</notextile>
<p>When called without arguments like this, it creates a form element that has the current page as its action and “post” as its method (some line breaks added for readability):</p>
<p>Sample output from <tt>form_tag</tt>:</p>
<notextile>
<div class="code_container">
<pre class="brush: xml; gutter: false; toolbar: false">
<form accept-charset="UTF-8" action="/home/index" method="post">
<div style="margin:0;padding:0">
<input name="utf8" type="hidden" value="&#x2713;" />
<input name="authenticity_token" type="hidden" value="f755bb0ed134b76c432144748a6d4b7a7ddf2b71" />
</div>
Form contents
</form>
</pre>
</div>
</notextile>
<p>If you carefully observe this output, you can see that the helper generated something you didn’t specify: a <tt>div</tt> element with two hidden input elements inside. The first input element with name <tt>utf8</tt> enforces browsers to properly respect your form’s character encoding and is generated for all forms whether action is “get” or “post”. Second input element with name <tt>authenticity_token</tt> is a security feature of Rails called <strong>cross-site request forgery protection</strong> and form helpers generate it for every form whose action is not “get” (provided that this security feature is enabled). You can read more about this in the <a href="./security.html#_cross_site_reference_forgery_csrf">Ruby On Rails Security Guide</a>.</p>
<div class='note'><p>Throughout this guide, this <tt>div</tt> with the hidden input elements will be stripped away to have clearer code samples.</p></div>
<h4 id="a-generic-search-form">1.1 A Generic Search Form</h4>
<p>Probably the most minimal form often seen on the web is a search form with a single text input for search terms. This form consists of:</p>
<ol>
<li>a form element with “<span class="caps">GET</span>” method,</li>
<li>a label for the input,</li>
<li>a text input element, and</li>
<li>a submit element.</li>
</ol>
<div class='warning'><p>Always use “<span class="caps">GET</span>” as the method for search forms. This allows users to bookmark a specific search and get back to it. More generally Rails encourages you to use the right <span class="caps">HTTP</span> verb for an action.</p></div>
<p>To create this form you will use <tt>form_tag</tt>, <tt>label_tag</tt>, <tt>text_field_tag</tt>, and <tt>submit_tag</tt>, respectively.</p>
<p>A basic search form</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
<%= form_tag(search_path, :method => "get") do %>
<%= label_tag(:q, "Search for:") %>
<%= text_field_tag(:q) %>
<%= submit_tag("Search") %>
<% end %>
</pre>
</div>
</notextile>
<div class='info'><p><tt>search_path</tt> can be a named route specified in “routes.rb” as: <br /><code>match "search" => "search"</code> This declares that path “/search” will be handled by action “search” belonging to controller “search”.</p></div>
<p>The above view code will result in the following markup:</p>
<notextile>
<div class="code_container">
<pre class="brush: xml; gutter: false; toolbar: false">
<form accept-charset="UTF-8" action="/search" method="get">
<label for="q">Search for:</label>
<input id="q" name="q" type="text" />
<input name="commit" type="submit" value="Search" />
</form>
</pre>
</div>
</notextile>
<p>Besides <tt>text_field_tag</tt> and <tt>submit_tag</tt>, there is a similar helper for <em>every</em> form control in <span class="caps">HTML</span>.</p>
<div class='info'><p>For every form input, an ID attribute is generated from its name (“q” in the example). These IDs can be very useful for <span class="caps">CSS</span> styling or manipulation of form controls with JavaScript.</p></div>
<h4 id="multiple-hashes-in-form-helper-calls">1.2 Multiple Hashes in Form Helper Calls</h4>
<p>By now you’ve seen that the <tt>form_tag</tt> helper accepts 2 arguments: the path for the action and an options hash. This hash specifies the method of form submission and <span class="caps">HTML</span> options such as the form element’s class.</p>
<p>As with the <tt>link_to</tt> helper, the path argument doesn’t have to be given a string. It can be a hash of <span class="caps">URL</span> parameters that Rails’ routing mechanism will turn into a valid <span class="caps">URL</span>. However, this is a bad way to pass multiple hashes as method arguments:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
form_tag(:controller => "people", :action => "search", :method => "get", :class => "nifty_form")
# => <form accept-charset="UTF-8" action="/people/search?method=get&class=nifty_form" method="post">
</pre>
</div>
</notextile>
<p>Here you wanted to pass two hashes, but the Ruby interpreter sees only one hash, so Rails will construct a <span class="caps">URL</span> with extraneous parameters. The correct way of passing multiple hashes as arguments is to delimit the first hash (or both hashes) with curly brackets:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
form_tag({:controller => "people", :action => "search"}, :method => "get", :class => "nifty_form")
# => <form accept-charset="UTF-8" action="/people/search" method="get" class="nifty_form">
</pre>
</div>
</notextile>
<p>This is a common pitfall when using form helpers, since many of them accept multiple hashes. So in future, if a helper produces unexpected output, make sure that you have delimited the hash parameters properly.</p>
<div class='warning'><p>Do not delimit the second hash without doing so with the first hash, otherwise your method invocation will result in an <tt>expecting tASSOC</tt> syntax error.</p></div>
<h4 id="helpers-for-generating-form-elements">1.3 Helpers for Generating Form Elements</h4>
<p>Rails provides a series of helpers for generating form elements such as checkboxes, text fields and radio buttons. These basic helpers, with names ending in _tag such as <tt>text_field_tag</tt> and <tt>check_box_tag</tt> generate just a single <tt><input></tt> element. The first parameter to these is always the name of the input. In the controller this name will be the key in the <tt>params</tt> hash used to get the value entered by the user. For example, if the form contains</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
<%= text_field_tag(:query) %>
</pre>
</div>
</notextile>
<p>then the controller code should use</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
params[:query]
</pre>
</div>
</notextile>
<p>to retrieve the value entered by the user. When naming inputs, be aware that Rails uses certain conventions that control whether values are at the top level of the <tt>params</tt> hash, inside an array or a nested hash and so on. You can read more about them in the parameter_names section. For details on the precise usage of these helpers, please refer to the <a href="http://api.rubyonrails.org/classes/ActionView/Helpers/FormTagHelper.html"><span class="caps">API</span> documentation</a>.</p>
<h5 id="checkboxes">1.3.1 Checkboxes</h5>
<p>Checkboxes are form controls that give the user a set of options they can enable or disable:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
<%= check_box_tag(:pet_dog) %>
<%= label_tag(:pet_dog, "I own a dog") %>
<%= check_box_tag(:pet_cat) %>
<%= label_tag(:pet_cat, "I own a cat") %>
</pre>
</div>
</notextile>
<p>output:</p>
<notextile>
<div class="code_container">
<pre class="brush: xml; gutter: false; toolbar: false">
<input id="pet_dog" name="pet_dog" type="checkbox" value="1" />
<label for="pet_dog">I own a dog</label>
<input id="pet_cat" name="pet_cat" type="checkbox" value="1" />
<label for="pet_cat">I own a cat</label>
</pre>
</div>
</notextile>
<p>The second parameter to <tt>check_box_tag</tt> is the value of the input. This is the value that will be submitted by the browser if the checkbox is ticked (i.e. the value that will be present in the <tt>params</tt> hash). With the above form you would check the value of <tt>params[:pet_dog]</tt> and <tt>params[:pet_cat]</tt> to see which pets the user owns.</p>
<h5 id="radio-buttons">1.3.2 Radio Buttons</h5>
<p>Radio buttons, while similar to checkboxes, are controls that specify a set of options in which they are mutually exclusive (i.e. the user can only pick one):</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
<%= radio_button_tag(:age, "child") %>
<%= label_tag(:age_child, "I am younger than 21") %>
<%= radio_button_tag(:age, "adult") %>
<%= label_tag(:age_adult, "I'm over 21") %>
</pre>
</div>
</notextile>
<p>output:</p>
<notextile>
<div class="code_container">
<pre class="brush: xml; gutter: false; toolbar: false">
<input id="age_child" name="age" type="radio" value="child" />
<label for="age_child">I am younger than 21</label>
<input id="age_adult" name="age" type="radio" value="adult" />
<label for="age_adult">I'm over 21</label>
</pre>
</div>
</notextile>
<p>As with <tt>check_box_tag</tt> the second parameter to <tt>radio_button_tag</tt> is the value of the input. Because these two radio buttons share the same name (age) the user will only be able to select one and <tt>params[:age]</tt> will contain either “child” or “adult”.</p>
<div class='warning'><p>Always use labels for each checkbox and radio button. They associate text with a specific option and provide a larger clickable region.</p></div>
<h4 id="other-helpers-of-interest">1.4 Other Helpers of Interest</h4>
<p>Other form controls worth mentioning are the text area, password input and hidden input:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
<%= text_area_tag(:message, "Hi, nice site", :size => "24x6") %>
<%= password_field_tag(:password) %>
<%= hidden_field_tag(:parent_id, "5") %>
</pre>
</div>
</notextile>
<p>output:</p>
<notextile>
<div class="code_container">
<pre class="brush: xml; gutter: false; toolbar: false">
<textarea id="message" name="message" cols="24" rows="6">Hi, nice site</textarea>
<input id="password" name="password" type="password" />
<input id="parent_id" name="parent_id" type="hidden" value="5" />
</pre>
</div>
</notextile>
<p>Hidden inputs are not shown to the user, but they hold data like any textual input. Values inside them can be changed with JavaScript.</p>
<div class='info'><p>If you’re using password input fields (for any purpose), you might want to prevent their values showing up in application logs by activating <tt>filter_parameter_logging(:password)</tt> in your ApplicationController.</p></div>
<h3 id="dealing-with-model-objects">2 Dealing with Model Objects</h3>
<h4 id="model-object-helpers">2.1 Model Object Helpers</h4>
<p>A particularly common task for a form is editing or creating a model object. While the <tt>*_tag</tt> helpers can certainly be used for this task they are somewhat verbose as for each tag you would have to ensure the correct parameter name is used and set the default value of the input appropriately. Rails provides helpers tailored to this task. These helpers lack the _tag suffix, for example <tt>text_field</tt>, <tt>text_area</tt>.</p>
<p>For these helpers the first argument is the name of an instance variable and the second is the name of a method (usually an attribute) to call on that object. Rails will set the value of the input control to the return value of that method for the object and set an appropriate input name. If your controller has defined <tt>@person</tt> and that person’s name is Henry then a form containing:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
<%= text_field(:person, :name) %>
</pre>
</div>
</notextile>
<p>will produce output similar to</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
<input id="person_name" name="person[name]" type="text" value="Henry"/>
</pre>
</div>
</notextile>
<p>Upon form submission the value entered by the user will be stored in <tt>params[:person][:name]</tt>. The <tt>params[:person]</tt> hash is suitable for passing to <tt>Person.new</tt> or, if <tt>@person</tt> is an instance of Person, <tt>@person.update_attributes</tt>. While the name of an attribute is the most common second parameter to these helpers this is not compulsory. In the example above, as long as person objects have a <tt>name</tt> and a <tt>name=</tt> method Rails will be happy.</p>
<div class='warning'><p>You must pass the name of an instance variable, i.e. <tt>:person</tt> or <tt>"person"</tt>, not an actual instance of your model object.</p></div>
<p>Rails provides helpers for displaying the validation errors associated with a model object. These are covered in detail by the <a href="./active_record_validations_callbacks.html#displaying-validation-errors-in-the-view">Active Record Validations and Callbacks</a> guide.</p>
<h4 id="binding-a-form-to-an-object">2.2 Binding a Form to an Object</h4>
<p>While this is an increase in comfort it is far from perfect. If Person has many attributes to edit then we would be repeating the name of the edited object many times. What we want to do is somehow bind a form to a model object, which is exactly what <tt>form_for</tt> does.</p>
<p>Assume we have a controller for dealing with articles <tt>app/controllers/articles_controller.rb</tt>:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
def new
@article = Article.new
end
</pre>
</div>
</notextile>
<p>The corresponding view <tt>app/views/articles/new.html.erb</tt> using <tt>form_for</tt> looks like this:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
<%= form_for @article, :url => { :action => "create" }, :html => {:class => "nifty_form"} do |f| %>
<%= f.text_field :title %>
<%= f.text_area :body, :size => "60x12" %>
<%= f.submit "Create" %>
<% end %>
</pre>
</div>
</notextile>
<p>There are a few things to note here:</p>
<ol>
<li><tt>@article</tt> is the actual object being edited.</li>
<li>There is a single hash of options. Routing options are passed in the <tt>:url</tt> hash, <span class="caps">HTML</span> options are passed in the <tt>:html</tt> hash.</li>
<li>The <tt>form_for</tt> method yields a <strong>form builder</strong> object (the <tt>f</tt> variable).</li>
<li>Methods to create form controls are called <strong>on</strong> the form builder object <tt>f</tt></li>
</ol>
<p>The resulting <span class="caps">HTML</span> is:</p>
<notextile>
<div class="code_container">
<pre class="brush: xml; gutter: false; toolbar: false">
<form accept-charset="UTF-8" action="/articles/create" method="post" class="nifty_form">
<input id="article_title" name="article[title]" size="30" type="text" />
<textarea id="article_body" name="article[body]" cols="60" rows="12"></textarea>
<input name="commit" type="submit" value="Create" />
</form>
</pre>
</div>
</notextile>
<p>The name passed to <tt>form_for</tt> controls the key used in <tt>params</tt> to access the form’s values. Here the name is <tt>article</tt> and so all the inputs have names of the form <tt>article[<em>attribute_name</em>]</tt>. Accordingly, in the <tt>create</tt> action <tt>params[:article]</tt> will be a hash with keys <tt>:title</tt> and <tt>:body</tt>. You can read more about the significance of input names in the parameter_names section.</p>
<p>The helper methods called on the form builder are identical to the model object helpers except that it is not necessary to specify which object is being edited since this is already managed by the form builder.</p>
<p>You can create a similar binding without actually creating <tt><form></tt> tags with the <tt>fields_for</tt> helper. This is useful for editing additional model objects with the same form. For example if you had a Person model with an associated ContactDetail model you could create a form for creating both like so:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
<%= form_for @person, :url => { :action => "create" } do |person_form| %>
<%= person_form.text_field :name %>
<%= fields_for @person.contact_detail do |contact_details_form| %>
<%= contact_details_form.text_field :phone_number %>
<% end %>
<% end %>
</pre>
</div>
</notextile>
<p>which produces the following output:</p>
<notextile>
<div class="code_container">
<pre class="brush: xml; gutter: false; toolbar: false">
<form accept-charset="UTF-8" action="/people/create" class="new_person" id="new_person" method="post">
<input id="person_name" name="person[name]" size="30" type="text" />
<input id="contact_detail_phone_number" name="contact_detail[phone_number]" size="30" type="text" />
</form>
</pre>
</div>
</notextile>
<p>The object yielded by <tt>fields_for</tt> is a form builder like the one yielded by <tt>form_for</tt> (in fact <tt>form_for</tt> calls <tt>fields_for</tt> internally).</p>
<h4 id="relying-on-record-identification">2.3 Relying on Record Identification</h4>
<p>The Article model is directly available to users of the application, so — following the best practices for developing with Rails — you should declare it <strong>a resource</strong>:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
resources :articles
</pre>
</div>
</notextile>
<div class='info'><p>Declaring a resource has a number of side-affects. See <a href="routing.html#resource-routing-the-rails-default">Rails Routing From the Outside In</a> for more information on setting up and using resources.</p></div>
<p>When dealing with RESTful resources, calls to <tt>form_for</tt> can get significantly easier if you rely on <strong>record identification</strong>. In short, you can just pass the model instance and have Rails figure out model name and the rest:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
## Creating a new article
# long-style:
form_for(@article, :url => articles_path)
# same thing, short-style (record identification gets used):
form_for(@article)
## Editing an existing article
# long-style:
form_for(@article, :url => article_path(@article), :html => { :method => "put" })
# short-style:
form_for(@article)
</pre>
</div>
</notextile>
<p>Notice how the short-style <tt>form_for</tt> invocation is conveniently the same, regardless of the record being new or existing. Record identification is smart enough to figure out if the record is new by asking <tt>record.new_record?</tt>. It also selects the correct path to submit to and the name based on the class of the object.</p>
<p>Rails will also automatically set the <tt>class</tt> and <tt>id</tt> of the form appropriately: a form creating an article would have <tt>id</tt> and <tt>class</tt> <tt>new_article</tt>. If you were editing the article with id 23, the <tt>class</tt> would be set to <tt>edit_article</tt> and the id to <tt>edit_article_23</tt>. These attributes will be omitted for brevity in the rest of this guide.</p>
<div class='warning'><p>When you’re using <span class="caps">STI</span> (single-table inheritance) with your models, you can’t rely on record identification on a subclass if only their parent class is declared a resource. You will have to specify the model name, <tt>:url</tt>, and <tt>:method</tt> explicitly.</p></div>
<h5 id="dealing-with-namespaces">2.3.1 Dealing with Namespaces</h5>
<p>If you have created namespaced routes, <tt>form_for</tt> has a nifty shorthand for that too. If your application has an admin namespace then</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
form_for [:admin, @article]
</pre>
</div>
</notextile>
<p>will create a form that submits to the articles controller inside the admin namespace (submitting to <tt>admin_article_path(@article)</tt> in the case of an update). If you have several levels of namespacing then the syntax is similar:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
form_for [:admin, :management, @article]
</pre>
</div>
</notextile>
<p>For more information on Rails’ routing system and the associated conventions, please see the <a href="routing.html">routing guide</a>.</p>
<h4 id="how-do-forms-with-put-or-delete-methods-work">2.4 How do forms with <span class="caps">PUT</span> or <span class="caps">DELETE</span> methods work?</h4>
<p>The Rails framework encourages RESTful design of your applications, which means you’ll be making a lot of “<span class="caps">PUT</span>” and “<span class="caps">DELETE</span>” requests (besides “<span class="caps">GET</span>” and “<span class="caps">POST</span>”). However, most browsers <em>don’t support</em> methods other than “<span class="caps">GET</span>” and “<span class="caps">POST</span>” when it comes to submitting forms.</p>
<p>Rails works around this issue by emulating other methods over <span class="caps">POST</span> with a hidden input named <tt>"_method"</tt>, which is set to reflect the desired method:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
form_tag(search_path, :method => "put")
</pre>
</div>
</notextile>
<p>output:</p>
<notextile>
<div class="code_container">
<pre class="brush: xml; gutter: false; toolbar: false">
<form accept-charset="UTF-8" action="/search" method="post">
<div style="margin:0;padding:0">
<input name="_method" type="hidden" value="put" />
<input name="utf8" type="hidden" value="&#x2713;" />
<input name="authenticity_token" type="hidden" value="f755bb0ed134b76c432144748a6d4b7a7ddf2b71" />
</div>
...
</pre>
</div>
</notextile>
<p>When parsing POSTed data, Rails will take into account the special <tt>_method</tt> parameter and acts as if the <span class="caps">HTTP</span> method was the one specified inside it (“<span class="caps">PUT</span>” in this example).</p>
<h3 id="making-select-boxes-with-ease">3 Making Select Boxes with Ease</h3>
<p>Select boxes in <span class="caps">HTML</span> require a significant amount of markup (one <tt>OPTION</tt> element for each option to choose from), therefore it makes the most sense for them to be dynamically generated.</p>
<p>Here is what the markup might look like:</p>
<notextile>
<div class="code_container">
<pre class="brush: xml; gutter: false; toolbar: false">
<select name="city_id" id="city_id">
<option value="1">Lisbon</option>
<option value="2">Madrid</option>
...
<option value="12">Berlin</option>
</select>
</pre>
</div>
</notextile>
<p>Here you have a list of cities whose names are presented to the user. Internally the application only wants to handle their IDs so they are used as the options’ value attribute. Let’s see how Rails can help out here.</p>
<h4 id="the-select-and-option-tags">3.1 The Select and Option Tags</h4>
<p>The most generic helper is <tt>select_tag</tt>, which — as the name implies — simply generates the <tt>SELECT</tt> tag that encapsulates an options string:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
<%= select_tag(:city_id, '<option value="1">Lisbon</option>...') %>
</pre>
</div>
</notextile>
<p>This is a start, but it doesn’t dynamically create the option tags. You can generate option tags with the <tt>options_for_select</tt> helper:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
<%= options_for_select([['Lisbon', 1], ['Madrid', 2], ...]) %>
output:
<option value="1">Lisbon</option>
<option value="2">Madrid</option>
...
</pre>
</div>
</notextile>
<p>The first argument to <tt>options_for_select</tt> is a nested array where each element has two elements: option text (city name) and option value (city id). The option value is what will be submitted to your controller. Often this will be the id of a corresponding database object but this does not have to be the case.</p>
<p>Knowing this, you can combine <tt>select_tag</tt> and <tt>options_for_select</tt> to achieve the desired, complete markup:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
<%= select_tag(:city_id, options_for_select(...)) %>
</pre>
</div>
</notextile>
<p><tt>options_for_select</tt> allows you to pre-select an option by passing its value.</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
<%= options_for_select([['Lisbon', 1], ['Madrid', 2], ...], 2) %>
output:
<option value="1">Lisbon</option>
<option value="2" selected="selected">Madrid</option>
...
</pre>
</div>
</notextile>
<p>Whenever Rails sees that the internal value of an option being generated matches this value, it will add the <tt>selected</tt> attribute to that option.</p>
<div class='info'><p>The second argument to <tt>options_for_select</tt> must be exactly equal to the desired internal value. In particular if the value is the integer 2 you cannot pass “2” to <tt>options_for_select</tt> — you must pass 2. Be aware of values extracted from the <tt>params</tt> hash as they are all strings.</p></div>
<h4 id="select-boxes-for-dealing-with-models">3.2 Select Boxes for Dealing with Models</h4>
<p>In most cases form controls will be tied to a specific database model and as you might expect Rails provides helpers tailored for that purpose. Consistent with other form helpers, when dealing with models you drop the <tt>_tag</tt> suffix from <tt>select_tag</tt>:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
# controller:
@person = Person.new(:city_id => 2)
</pre>
</div>
</notextile>
<notextile>
<div class="code_container">
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
# view:
<%= select(:person, :city_id, [['Lisbon', 1], ['Madrid', 2], ...]) %>
</pre>
</div>
</notextile>
<p>Notice that the third parameter, the options array, is the same kind of argument you pass to <tt>options_for_select</tt>. One advantage here is that you don’t have to worry about pre-selecting the correct city if the user already has one — Rails will do this for you by reading from the <tt>@person.city_id</tt> attribute.</p>
<p>As with other helpers, if you were to use the <tt>select</tt> helper on a form builder scoped to the <tt>@person</tt> object, the syntax would be:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
# select on a form builder
<%= f.select(:city_id, ...) %>
</pre>
</div>
</notextile>
<div class='warning'><p>If you are using <tt>select</tt> (or similar helpers such as <tt>collection_select</tt>, <tt>select_tag</tt>) to set a <tt>belongs_to</tt> association you must pass the name of the foreign key (in the example above <tt>city_id</tt>), not the name of association itself. If you specify <tt>city</tt> instead of <tt>city_id</tt> Active Record will raise an error along the lines of <tt> ActiveRecord::AssociationTypeMismatch: City(#17815740) expected, got String(#1138750) </tt> when you pass the <tt>params</tt> hash to <tt>Person.new</tt> or <tt>update_attributes</tt>. Another way of looking at this is that form helpers only edit attributes. You should also be aware of the potential security ramifications of allowing users to edit foreign keys directly. You may wish to consider the use of <tt>attr_protected</tt> and <tt>attr_accessible</tt>. For further details on this, see the <a href="security.html#_mass_assignment">Ruby On Rails Security Guide</a>.</p></div>
<h4 id="option-tags-from-a-collection-of-arbitrary-objects">3.3 Option Tags from a Collection of Arbitrary Objects</h4>
<p>Generating options tags with <tt>options_for_select</tt> requires that you create an array containing the text and value for each option. But what if you had a City model (perhaps an Active Record one) and you wanted to generate option tags from a collection of those objects? One solution would be to make a nested array by iterating over them:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
<% cities_array = City.all.map { |city| [city.name, city.id] } %>
<%= options_for_select(cities_array) %>
</pre>
</div>
</notextile>
<p>This is a perfectly valid solution, but Rails provides a less verbose alternative: <tt>options_from_collection_for_select</tt>. This helper expects a collection of arbitrary objects and two additional arguments: the names of the methods to read the option <strong>value</strong> and <strong>text</strong> from, respectively:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
<%= options_from_collection_for_select(City.all, :id, :name) %>
</pre>
</div>
</notextile>
<p>As the name implies, this only generates option tags. To generate a working select box you would need to use it in conjunction with <tt>select_tag</tt>, just as you would with <tt>options_for_select</tt>. When working with model objects, just as <tt>select</tt> combines <tt>select_tag</tt> and <tt>options_for_select</tt>, <tt>collection_select</tt> combines <tt>select_tag</tt> with <tt>options_from_collection_for_select</tt>.</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
<%= collection_select(:person, :city_id, City.all, :id, :name) %>
</pre>
</div>
</notextile>
<p>To recap, <tt>options_from_collection_for_select</tt> is to <tt>collection_select</tt> what <tt>options_for_select</tt> is to <tt>select</tt>.</p>
<div class='note'><p>Pairs passed to <tt>options_for_select</tt> should have the name first and the id second, however with <tt>options_from_collection_for_select</tt> the first argument is the value method and the second the text method.</p></div>
<h4 id="time-zone-and-country-select">3.4 Time Zone and Country Select</h4>
<p>To leverage time zone support in Rails, you have to ask your users what time zone they are in. Doing so would require generating select options from a list of pre-defined TimeZone objects using <tt>collection_select</tt>, but you can simply use the <tt>time_zone_select</tt> helper that already wraps this:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
<%= time_zone_select(:person, :time_zone) %>
</pre>
</div>
</notextile>
<p>There is also <tt>time_zone_options_for_select</tt> helper for a more manual (therefore more customizable) way of doing this. Read the <span class="caps">API</span> documentation to learn about the possible arguments for these two methods.</p>
<p>Rails <em>used</em> to have a <tt>country_select</tt> helper for choosing countries, but this has been extracted to the <a href="http://github.com/rails/country_select/tree/master">country_select plugin</a>. When using this, be aware that the exclusion or inclusion of certain names from the list can be somewhat controversial (and was the reason this functionality was extracted from Rails).</p>
<h3 id="using-date-and-time-form-helpers">4 Using Date and Time Form Helpers</h3>
<p>The date and time helpers differ from all the other form helpers in two important respects:</p>
<ol>
<li>Dates and times are not representable by a single input element. Instead you have several, one for each component (year, month, day etc.) and so there is no single value in your <tt>params</tt> hash with your date or time.</li>
<li>Other helpers use the <tt>_tag</tt> suffix to indicate whether a helper is a barebones helper or one that operates on model objects. With dates and times, <tt>select_date</tt>, <tt>select_time</tt> and <tt>select_datetime</tt> are the barebones helpers, <tt>date_select</tt>, <tt>time_select</tt> and <tt>datetime_select</tt> are the equivalent model object helpers.</li>
</ol>
<p>Both of these families of helpers will create a series of select boxes for the different components (year, month, day etc.).</p>
<h4 id="barebones-helpers">4.1 Barebones Helpers</h4>
<p>The <tt>select_*</tt> family of helpers take as their first argument an instance of Date, Time or DateTime that is used as the currently selected value. You may omit this parameter, in which case the current date is used. For example</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
<%= select_date Date.today, :prefix => :start_date %>
</pre>
</div>
</notextile>
<p>outputs (with actual option values omitted for brevity)</p>
<notextile>
<div class="code_container">
<pre class="brush: xml; gutter: false; toolbar: false">
<select id="start_date_year" name="start_date[year]"> ... </select>
<select id="start_date_month" name="start_date[month]"> ... </select>
<select id="start_date_day" name="start_date[day]"> ... </select>
</pre>
</div>
</notextile>
<p>The above inputs would result in <tt>params[:start_date]</tt> being a hash with keys <tt>:year</tt>, <tt>:month</tt>, <tt>:day</tt>. To get an actual Time or Date object you would have to extract these values and pass them to the appropriate constructor, for example</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
Date.civil(params[:start_date][:year].to_i, params[:start_date][:month].to_i, params[:start_date][:day].to_i)
</pre>
</div>
</notextile>
<p>The <tt>:prefix</tt> option is the key used to retrieve the hash of date components from the <tt>params</tt> hash. Here it was set to <tt>start_date</tt>, if omitted it will default to <tt>date</tt>.</p>
<h4 id="select-model-object-helpers">4.2 Model Object Helpers</h4>
<p><tt>select_date</tt> does not work well with forms that update or create Active Record objects as Active Record expects each element of the <tt>params</tt> hash to correspond to one attribute.
The model object helpers for dates and times submit parameters with special names, when Active Record sees parameters with such names it knows they must be combined with the other parameters and given to a constructor appropriate to the column type. For example:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
<%= date_select :person, :birth_date %>
</pre>
</div>
</notextile>
<p>outputs (with actual option values omitted for brevity)</p>
<notextile>
<div class="code_container">
<pre class="brush: xml; gutter: false; toolbar: false">
<select id="person_birth_date_1i" name="person[birth_date(1i)]"> ... </select>
<select id="person_birth_date_2i" name="person[birth_date(2i)]"> ... </select>
<select id="person_birth_date_3i" name="person[birth_date(3i)]"> ... </select>
</pre>
</div>
</notextile>
<p>which results in a <tt>params</tt> hash like</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
{:person => {'birth_date(1i)' => '2008', 'birth_date(2i)' => '11', 'birth_date(3i)' => '22'}}
</pre>
</div>
</notextile>
<p>When this is passed to <tt>Person.new</tt> (or <tt>update_attributes</tt>), Active Record spots that these parameters should all be used to construct the <tt>birth_date</tt> attribute and uses the suffixed information to determine in which order it should pass these parameters to functions such as <tt>Date.civil</tt>.</p>
<h4 id="common-options">4.3 Common Options</h4>
<p>Both families of helpers use the same core set of functions to generate the individual select tags and so both accept largely the same options. In particular, by default Rails will generate year options 5 years either side of the current year. If this is not an appropriate range, the <tt>:start_year</tt> and <tt>:end_year</tt> options override this. For an exhaustive list of the available options, refer to the <a href="http://api.rubyonrails.org/classes/ActionView/Helpers/DateHelper.html"><span class="caps">API</span> documentation</a>.</p>
<p>As a rule of thumb you should be using <tt>date_select</tt> when working with model objects and <tt>select_date</tt> in other cases, such as a search form which filters results by date.</p>
<div class='note'><p>In many cases the built-in date pickers are clumsy as they do not aid the user in working out the relationship between the date and the day of the week.</p></div>
<h4 id="individual-components">4.4 Individual Components</h4>
<p>Occasionally you need to display just a single date component such as a year or a month. Rails provides a series of helpers for this, one for each component <tt>select_year</tt>, <tt>select_month</tt>, <tt>select_day</tt>, <tt>select_hour</tt>, <tt>select_minute</tt>, <tt>select_second</tt>. These helpers are fairly straightforward. By default they will generate an input field named after the time component (for example “year” for <tt>select_year</tt>, “month” for <tt>select_month</tt> etc.) although this can be overriden with the <tt>:field_name</tt> option. The <tt>:prefix</tt> option works in the same way that it does for <tt>select_date</tt> and <tt>select_time</tt> and has the same default value.</p>
<p>The first parameter specifies which value should be selected and can either be an instance of a Date, Time or DateTime, in which case the relevant component will be extracted, or a numerical value. For example</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
<%= select_year(2009) %>
<%= select_year(Time.now) %>
</pre>
</div>
</notextile>
<p>will produce the same output if the current year is 2009 and the value chosen by the user can be retrieved by <tt>params[:date][:year]</tt>.</p>
<h3 id="uploading-files">5 Uploading Files</h3>
<p>A common task is uploading some sort of file, whether it’s a picture of a person or a <span class="caps">CSV</span> file containing data to process. The most important thing to remember with file uploads is that the rendered form’s encoding <strong><span class="caps">MUST</span></strong> be set to “multipart/form-data”. If you use <tt>form_for</tt>, this is done automatically. If you use <tt>form_tag</tt>, you must set it yourself, as per the following example.</p>
<p>The following two forms both upload a file.</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
<%= form_tag({:action => :upload}, :multipart => true) do %>
<%= file_field_tag 'picture' %>
<% end %>
<%= form_for @person do |f| %>
<%= f.file_field :picture %>
<% end %>
</pre>
</div>
</notextile>
<div class='note'><p>Since Rails 3.1, forms rendered using <tt>form_for</tt> have their encoding set to <tt>multipart/form-data</tt> automatically once a <tt>file_field</tt> is used inside the block. Previous versions required you to set this explicitly.</p></div>
<p>Rails provides the usual pair of helpers: the barebones <tt>file_field_tag</tt> and the model oriented <tt>file_field</tt>. The only difference with other helpers is that you cannot set a default value for file inputs as this would have no meaning. As you would expect in the first case the uploaded file is in <tt>params[:picture]</tt> and in the second case in <tt>params[:person][:picture]</tt>.</p>
<h4 id="what-gets-uploaded">5.1 What Gets Uploaded</h4>
<p>The object in the <tt>params</tt> hash is an instance of a subclass of IO. Depending on the size of the uploaded file it may in fact be a StringIO or an instance of File backed by a temporary file. In both cases the object will have an <tt>original_filename</tt> attribute containing the name the file had on the user’s computer and a <tt>content_type</tt> attribute containing the <span class="caps">MIME</span> type of the uploaded file. The following snippet saves the uploaded content in <tt>#{Rails.root}/public/uploads</tt> under the same name as the original file (assuming the form was the one in the previous example).</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
def upload
uploaded_io = params[:person][:picture]
File.open(Rails.root.join('public', 'uploads', uploaded_io.original_filename), 'w') do |file|
file.write(uploaded_io.read)
end
end
</pre>
</div>
</notextile>
<p>Once a file has been uploaded, there are a multitude of potential tasks, ranging from where to store the files (on disk, Amazon S3, etc) and associating them with models to resizing image files and generating thumbnails. The intricacies of this are beyond the scope of this guide, but there are several plugins designed to assist with these. Two of the better known ones are <a href="http://github.com/technoweenie/attachment_fu">Attachment-Fu</a> and <a href="http://www.thoughtbot.com/projects/paperclip">Paperclip</a>.</p>
<div class='note'><p>If the user has not selected a file the corresponding parameter will be an empty string.</p></div>
<h4 id="dealing-with-ajax">5.2 Dealing with Ajax</h4>
<p>Unlike other forms making an asynchronous file upload form is not as simple as replacing <tt>form_for</tt> with <tt>remote_form_for</tt>. With an Ajax form the serialization is done by JavaScript running inside the browser and since JavaScript cannot read files from your hard drive the file cannot be uploaded. The most common workaround is to use an invisible iframe that serves as the target for the form submission.</p>
<h3 id="customizing-form-builders">6 Customizing Form Builders</h3>
<p>As mentioned previously the object yielded by <tt>form_for</tt> and <tt>fields_for</tt> is an instance of FormBuilder (or a subclass thereof). Form builders encapsulate the notion of displaying form elements for a single object. While you can of course write helpers for your forms in the usual way you can also subclass FormBuilder and add the helpers there. For example</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
<%= form_for @person do |f| %>
<%= text_field_with_label f, :first_name %>
<% end %>
</pre>
</div>
</notextile>
<p>can be replaced with</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
<%= form_for @person, :builder => LabellingFormBuilder do |f| %>
<%= f.text_field :first_name %>
<% end %>
</pre>
</div>
</notextile>
<p>by defining a LabellingFormBuilder class similar to the following:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class LabellingFormBuilder < ActionView::Helpers::FormBuilder
def text_field(attribute, options={})
label(attribute) + super
end
end
</pre>
</div>
</notextile>
<p>If you reuse this frequently you could define a <tt>labeled_form_for</tt> helper that automatically applies the <tt>:builder => LabellingFormBuilder</tt> option.</p>
<p>The form builder used also determines what happens when you do</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
<%= render :partial => f %>
</pre>
</div>
</notextile>
<p>If <tt>f</tt> is an instance of FormBuilder then this will render the <tt>form</tt> partial, setting the partial’s object to the form builder. If the form builder is of class LabellingFormBuilder then the <tt>labelling_form</tt> partial would be rendered instead.</p>
<h3 id="understanding-parameter-naming-conventions">7 Understanding Parameter Naming Conventions</h3>
<p>As you’ve seen in the previous sections, values from forms can be at the top level of the <tt>params</tt> hash or nested in another hash. For example in a standard <tt>create</tt>
action for a Person model, <tt>params[:model]</tt> would usually be a hash of all the attributes for the person to create. The <tt>params</tt> hash can also contain arrays, arrays of hashes and so on.</p>
<p>Fundamentally <span class="caps">HTML</span> forms don’t know about any sort of structured data, all they generate is name–value pairs, where pairs are just plain strings. The arrays and hashes you see in your application are the result of some parameter naming conventions that Rails uses.</p>
<div class='info'><p>You may find you can try out examples in this section faster by using the console to directly invoke Rails’ parameter parser. For example,</p></div>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
ActionController::UrlEncodedPairParser.parse_query_parameters "name=fred&phone=0123456789"
# => {"name"=>"fred", "phone"=>"0123456789"}
</pre>
</div>
</notextile>
<h4 id="basic-structures">7.1 Basic Structures</h4>
<p>The two basic structures are arrays and hashes. Hashes mirror the syntax used for accessing the value in <tt>params</tt>. For example if a form contains</p>
<notextile>
<div class="code_container">
<pre class="brush: xml; gutter: false; toolbar: false">
<input id="person_name" name="person[name]" type="text" value="Henry"/>
</pre>
</div>
</notextile>
<p>the <tt>params</tt> hash will contain</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
{'person' => {'name' => 'Henry'}}
</pre>
</div>
</notextile>
<p>and <tt>params[:person][:name]</tt> will retrieve the submitted value in the controller.</p>
<p>Hashes can be nested as many levels as required, for example</p>
<notextile>
<div class="code_container">
<pre class="brush: xml; gutter: false; toolbar: false">
<input id="person_address_city" name="person[address][city]" type="text" value="New York"/>
</pre>
</div>
</notextile>
<p>will result in the <tt>params</tt> hash being</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
{'person' => {'address' => {'city' => 'New York'}}}
</pre>
</div>
</notextile>
<p>Normally Rails ignores duplicate parameter names. If the parameter name contains an empty set of square brackets [] then they will be accumulated in an array. If you wanted people to be able to input multiple phone numbers, you could place this in the form:</p>
<notextile>
<div class="code_container">
<pre class="brush: xml; gutter: false; toolbar: false">
<input name="person[phone_number][]" type="text"/>
<input name="person[phone_number][]" type="text"/>
<input name="person[phone_number][]" type="text"/>
</pre>
</div>
</notextile>
<p>This would result in <tt>params[:person][:phone_number]</tt> being an array.</p>
<h4 id="combining-them">7.2 Combining Them</h4>
<p>We can mix and match these two concepts. For example, one element of a hash might be an array as in the previous example, or you can have an array of hashes. For example a form might let you create any number of addresses by repeating the following form fragment</p>
<notextile>
<div class="code_container">
<pre class="brush: xml; gutter: false; toolbar: false">
<input name="addresses[][line1]" type="text"/>
<input name="addresses[][line2]" type="text"/>
<input name="addresses[][city]" type="text"/>
</pre>
</div>
</notextile>
<p>This would result in <tt>params[:addresses]</tt> being an array of hashes with keys <tt>line1</tt>, <tt>line2</tt> and <tt>city</tt>. Rails decides to start accumulating values in a new hash whenever it encounters an input name that already exists in the current hash.</p>
<p>There’s a restriction, however, while hashes can be nested arbitrarily, only one level of “arrayness” is allowed. Arrays can be usually replaced by hashes, for example instead of having an array of model objects one can have a hash of model objects keyed by their id, an array index or some other parameter.</p>
<div class='warning'><p>Array parameters do not play well with the <tt>check_box</tt> helper. According to the <span class="caps">HTML</span> specification unchecked checkboxes submit no value. However it is often convenient for a checkbox to always submit a value. The <tt>check_box</tt> helper fakes this by creating an auxiliary hidden input with the same name. If the checkbox is unchecked only the hidden input is submitted and if it is checked then both are submitted but the value submitted by the checkbox takes precedence. When working with array parameters this duplicate submission will confuse Rails since duplicate input names are how it decides when to start a new array element. It is preferable to either use <tt>check_box_tag</tt> or to use hashes instead of arrays.</p></div>
<h4 id="using-form-helpers">7.3 Using Form Helpers</h4>
<p>The previous sections did not use the Rails form helpers at all. While you can craft the input names yourself and pass them directly to helpers such as <tt>text_field_tag</tt> Rails also provides higher level support. The two tools at your disposal here are the name parameter to <tt>form_for</tt> and <tt>fields_for</tt> and the <tt>:index</tt> option that helpers take.</p>
<p>You might want to render a form with a set of edit fields for each of a person’s addresses. For example:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
<%= form_for @person do |person_form| %>
<%= person_form.text_field :name %>
<% for address in @person.addresses %>
<%= person_form.fields_for address, :index => address do |address_form|%>
<%= address_form.text_field :city %>
<% end %>
<% end %>
<% end %>
</pre>
</div>
</notextile>
<p>Assuming the person had two addresses, with ids 23 and 45 this would create output similar to this:</p>
<notextile>
<div class="code_container">
<pre class="brush: xml; gutter: false; toolbar: false">
<form accept-charset="UTF-8" action="/people/1" class="edit_person" id="edit_person_1" method="post">
<input id="person_name" name="person[name]" size="30" type="text" />
<input id="person_address_23_city" name="person[address][23][city]" size="30" type="text" />
<input id="person_address_45_city" name="person[address][45][city]" size="30" type="text" />
</form>
</pre>
</div>
</notextile>
<p>This will result in a <tt>params</tt> hash that looks like</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
{'person' => {'name' => 'Bob', 'address' => {'23' => {'city' => 'Paris'}, '45' => {'city' => 'London'}}}}
</pre>
</div>
</notextile>
<p>Rails knows that all these inputs should be part of the person hash because you called <tt>fields_for</tt> on the first form builder. By specifying an <tt>:index</tt> option you’re telling Rails that instead of naming the inputs <tt>person[address][city]</tt> it should insert that index surrounded by [] between the address and the city. If you pass an Active Record object as we did then Rails will call <tt>to_param</tt> on it, which by default returns the database id. This is often useful as it is then easy to locate which Address record should be modified. You can pass numbers with some other significance, strings or even <tt>nil</tt> (which will result in an array parameter being created).</p>
<p>To create more intricate nestings, you can specify the first part of the input name (<tt>person[address]</tt> in the previous example) explicitly, for example</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
<%= fields_for 'person[address][primary]', address, :index => address do |address_form| %>
<%= address_form.text_field :city %>
<% end %>
</pre>
</div>
</notextile>
<p>will create inputs like</p>
<notextile>
<div class="code_container">
<pre class="brush: xml; gutter: false; toolbar: false">
<input id="person_address_primary_1_city" name="person[address][primary][1][city]" size="30" type="text" value="bologna" />
</pre>
</div>
</notextile>
<p>As a general rule the final input name is the concatenation of the name given to <tt>fields_for</tt>/<tt>form_for</tt>, the index value and the name of the attribute. You can also pass an <tt>:index</tt> option directly to helpers such as <tt>text_field</tt>, but it is usually less repetitive to specify this at the form builder level rather than on individual input controls.</p>
<p>As a shortcut you can append [] to the name and omit the <tt>:index</tt> option. This is the same as specifying <tt>:index => address</tt> so</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
<%= fields_for 'person[address][primary][]', address do |address_form| %>
<%= address_form.text_field :city %>
<% end %>
</pre>
</div>
</notextile>
<p>produces exactly the same output as the previous example.</p>
<h3 id="building-complex-forms">8 Building Complex Forms</h3>
<p>Many apps grow beyond simple forms editing a single object. For example when creating a Person you might want to allow the user to (on the same form) create multiple address records (home, work, etc.). When later editing that person the user should be able to add, remove or amend addresses as necessary. While this guide has shown you all the pieces necessary to handle this, Rails does not yet have a standard end-to-end way of accomplishing this, but many have come up with viable approaches. These include:</p>
<ul>
<li>As of Rails 2.3, Rails includes <a href="./2_3_release_notes.html#nested-attributes">Nested Attributes</a> and <a href="./2_3_release_notes.html#nested-object-forms">Nested Object Forms</a></li>
<li>Ryan Bates’ series of Railscasts on <a href="http://railscasts.com/episodes/75">complex forms</a></li>
<li>Handle Multiple Models in One Form from <a href="http://media.pragprog.com/titles/fr_arr/multiple_models_one_form.pdf">Advanced Rails Recipes</a></li>
<li>Eloy Duran’s <a href="http://github.com/alloy/complex-form-examples/">complex-forms-examples</a> application</li>
<li>Lance Ivy’s <a href="http://github.com/cainlevy/nested_assignment/tree/master">nested_assignment</a> plugin and <a href="http://github.com/cainlevy/complex-form-examples/tree/cainlevy">sample application</a></li>
<li>James Golick’s <a href="http://github.com/jamesgolick/attribute_fu">attribute_fu</a> plugin</li>
</ul>
<h3 id="changelog">9 Changelog</h3>
<ul>
<li>April 6, 2010: Fixed document to validate <span class="caps">XHTML</span> 1.0 Strict. <a href="http://jaimeiniesta.com">Jaime Iniesta</a></li>
</ul>
<h3 id="authors">10 Authors</h3>
<ul>
<li>Mislav Marohnić <[email protected]></li>
<li><a href="credits.html#fcheung">Frederick Cheung</a></li>
</ul>
<h3>Feedback</h3>
<p>
You're encouraged to help in keeping the quality of this guide.
</p>
<p>
If you see any typos or factual errors you are confident to
patch, please clone <a href="https://github.com/lifo/docrails">docrails</a>
and push the change yourself. That branch of Rails has public write access.
Commits are still reviewed, but that happens after you've submitted your
contribution. <a href="https://github.com/lifo/docrails">docrails</a> is
cross-merged with master periodically.
</p>
<p>
You may also find incomplete content, or stuff that is not up to date.
Please do add any missing documentation for master. Check the
<a href="ruby_on_rails_guides_guidelines.html">Ruby on Rails Guides Guidelines</a>
for style and conventions.
</p>
<p>
Issues may also be reported in <a href="https://github.com/lifo/docrails/issues">Github</a>.
</p>
<p>And last but not least, any kind of discussion regarding Ruby on Rails
documentation is very welcome in the <a href="http://groups.google.com/group/rubyonrails-docs">rubyonrails-docs mailing list</a>.
</p>
</div>