-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathaction_view_overview.html
1388 lines (1220 loc) · 83.9 KB
/
action_view_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 View 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>
</head>
<body class="guide">
<div>
<img src="images/edge_badge.png" alt="edge-badge" id="edge-badge" />
</div>
<div id="topNav">
<div class="wrapper">
<strong class="more-info-label">Veja mais em <a href="http://rubyonrails.org/">rubyonrails.org:</a> </strong>
<span class="red-button more-info-button">
Mais Ruby on Rails
</span>
<ul class="more-info-links s-hidden">
<li class="more-info"><a href="https://weblog.rubyonrails.org/">Blog</a></li>
<li class="more-info"><a href="https://guides.rubyonrails.org/">Guia</a></li>
<li class="more-info"><a href="http://api.rubyonrails.org/">API</a></li>
<li class="more-info"><a href="https://stackoverflow.com/questions/tagged/ruby-on-rails">Pedir ajuda</a></li>
<li class="more-info"><a href="https://github.com/rails/rails">Contribuir no GitHub</a></li>
</ul>
</div>
</div>
<div id="header">
<div class="wrapper clearfix">
<h1><a href="index.html" title="Return to home page">Guides.rubyonrails.org</a></h1>
<ul class="nav">
<li><a class="nav-item" href="index.html">Home</a></li>
<li class="guides-index guides-index-large">
<a href="index.html" id="guidesMenu" class="guides-index-item nav-item">Guias</a>
<div id="guides" class="clearfix" style="display: none;">
<hr />
<div class="guides-section-container">
<div class="guides-section">
<dt>Comece Aqui</dt>
</div>
<div class="guides-section">
<dt>Models</dt>
</div>
<div class="guides-section">
<dt>Views</dt>
</div>
<div class="guides-section">
<dt>Controllers</dt>
</div>
<div class="guides-section">
<dt>Other Components</dt>
</div>
<div class="guides-section">
<dt>Digging Deeper</dt>
</div>
<div class="guides-section">
<dt>Extending Rails</dt>
<dd><a href="rails_on_rack.html">Rails on Rack</a></dd>
<dd><a href="generators.html">Creating and Customizing Rails Generators & Templates</a></dd>
</div>
<div class="guides-section">
<dt>Contributions</dt>
<dd><a href="contributing_to_ruby_on_rails.html">Contributing to Ruby on Rails</a></dd>
<dd><a href="api_documentation_guidelines.html">API Documentation Guidelines</a></dd>
<dd><a href="ruby_on_rails_guides_guidelines.html">Guides Guidelines</a></dd>
</div>
<div class="guides-section">
<dt>Policies</dt>
<dd><a href="maintenance_policy.html">Maintenance Policy</a></dd>
</div>
<div class="guides-section">
<dt>Release Notes</dt>
<dd><a href="upgrading_ruby_on_rails.html">Upgrading Ruby on Rails</a></dd>
<dd><a href="5_2_release_notes.html">Version 5.2 - April 2018</a></dd>
<dd><a href="5_1_release_notes.html">Version 5.1 - April 2017</a></dd>
<dd><a href="5_0_release_notes.html">Version 5.0 - June 2016</a></dd>
<dd><a href="4_2_release_notes.html">Version 4.2 - December 2014</a></dd>
<dd><a href="4_1_release_notes.html">Version 4.1 - April 2014</a></dd>
<dd><a href="4_0_release_notes.html">Version 4.0 - June 2013</a></dd>
<dd><a href="3_2_release_notes.html">Version 3.2 - January 2012</a></dd>
<dd><a href="3_1_release_notes.html">Version 3.1 - August 2011</a></dd>
<dd><a href="3_0_release_notes.html">Version 3.0 - August 2010</a></dd>
<dd><a href="2_3_release_notes.html">Version 2.3 - March 2009</a></dd>
<dd><a href="2_2_release_notes.html">Version 2.2 - November 2008</a></dd>
</div>
</div>
</div>
</li>
<li><a class="nav-item" href="contributing_to_ruby_on_rails.html">Contribua</a></li>
<li class="guides-index guides-index-small">
<select class="guides-index-item nav-item">
<option value="index.html">Guias</option>
<optgroup label="Comece Aqui">
</optgroup>
<optgroup label="Models">
</optgroup>
<optgroup label="Views">
</optgroup>
<optgroup label="Controllers">
</optgroup>
<optgroup label="Other Components">
</optgroup>
<optgroup label="Digging Deeper">
</optgroup>
<optgroup label="Extending Rails">
<option value="rails_on_rack.html">Rails on Rack</option>
<option value="generators.html">Creating and Customizing Rails Generators & Templates</option>
</optgroup>
<optgroup label="Contributions">
<option value="contributing_to_ruby_on_rails.html">Contributing to Ruby on Rails</option>
<option value="api_documentation_guidelines.html">API Documentation Guidelines</option>
<option value="ruby_on_rails_guides_guidelines.html">Guides Guidelines</option>
</optgroup>
<optgroup label="Policies">
<option value="maintenance_policy.html">Maintenance Policy</option>
</optgroup>
<optgroup label="Release Notes">
<option value="upgrading_ruby_on_rails.html">Upgrading Ruby on Rails</option>
<option value="5_2_release_notes.html">Version 5.2 - April 2018</option>
<option value="5_1_release_notes.html">Version 5.1 - April 2017</option>
<option value="5_0_release_notes.html">Version 5.0 - June 2016</option>
<option value="4_2_release_notes.html">Version 4.2 - December 2014</option>
<option value="4_1_release_notes.html">Version 4.1 - April 2014</option>
<option value="4_0_release_notes.html">Version 4.0 - June 2013</option>
<option value="3_2_release_notes.html">Version 3.2 - January 2012</option>
<option value="3_1_release_notes.html">Version 3.1 - August 2011</option>
<option value="3_0_release_notes.html">Version 3.0 - August 2010</option>
<option value="2_3_release_notes.html">Version 2.3 - March 2009</option>
<option value="2_2_release_notes.html">Version 2.2 - November 2008</option>
</optgroup>
</select>
</li>
</ul>
</div>
</div>
<hr class="hide" />
<div id="feature">
<div class="wrapper">
<h2>Action View Overview</h2><p>After reading this guide, you will know:</p>
<ul>
<li>What Action View is and how to use it with Rails.</li>
<li>How best to use templates, partials, and layouts.</li>
<li>What helpers are provided by Action View.</li>
<li>How to use localized views.</li>
</ul>
<div id="subCol">
<h3 class="chapter"><img src="images/chapters_icon.gif" alt="" />Chapters</h3>
<ol class="chapters">
<li><a href="#what-is-action-view-questionmark">What is Action View?</a></li>
<li><a href="#using-action-view-with-rails">Using Action View with Rails</a></li>
<li>
<a href="#templates-partials-and-layouts">Templates, Partials, and Layouts</a>
<ul>
<li><a href="#templates">Templates</a></li>
<li><a href="#partials">Partials</a></li>
<li><a href="#layouts">Layouts</a></li>
</ul>
</li>
<li><a href="#partial-layouts">Partial Layouts</a></li>
<li>
<a href="#view-paths">View Paths</a>
<ul>
<li><a href="#prepend-view-path">Prepend view path</a></li>
<li><a href="#append-view-path">Append view path</a></li>
</ul>
</li>
<li>
<a href="#overview-of-helpers-provided-by-action-view">Overview of helpers provided by Action View</a>
<ul>
<li><a href="#assettaghelper">AssetTagHelper</a></li>
<li><a href="#atomfeedhelper">AtomFeedHelper</a></li>
<li><a href="#benchmarkhelper">BenchmarkHelper</a></li>
<li><a href="#cachehelper">CacheHelper</a></li>
<li><a href="#capturehelper">CaptureHelper</a></li>
<li><a href="#datehelper">DateHelper</a></li>
<li><a href="#debughelper">DebugHelper</a></li>
<li><a href="#formhelper">FormHelper</a></li>
<li><a href="#formoptionshelper">FormOptionsHelper</a></li>
<li><a href="#formtaghelper">FormTagHelper</a></li>
<li><a href="#javascripthelper">JavaScriptHelper</a></li>
<li><a href="#numberhelper">NumberHelper</a></li>
<li><a href="#sanitizehelper">SanitizeHelper</a></li>
<li><a href="#csrfhelper">CsrfHelper</a></li>
</ul>
</li>
<li><a href="#localized-views">Localized Views</a></li>
</ol>
</div>
</div>
</div>
<div id="container">
<div class="wrapper">
<div id="mainCol">
<h3 id="what-is-action-view-questionmark"><a class="anchorlink" href="#what-is-action-view-questionmark">1 What is Action View?</a></h3><p>In Rails, web requests are handled by <a href="action_controller_overview.html">Action Controller</a> and Action View. Typically, Action Controller is concerned with communicating with the database and performing CRUD actions where necessary. Action View is then responsible for compiling the response.</p><p>Action View templates are written using embedded Ruby in tags mingled with HTML. To avoid cluttering the templates with boilerplate code, a number of helper classes provide common behavior for forms, dates, and strings. It's also easy to add new helpers to your application as it evolves.</p><div class="note"><p>Some features of Action View are tied to Active Record, but that doesn't mean Action View depends on Active Record. Action View is an independent package that can be used with any sort of Ruby libraries.</p></div><h3 id="using-action-view-with-rails"><a class="anchorlink" href="#using-action-view-with-rails">2 Using Action View with Rails</a></h3><p>For each controller there is an associated directory in the <code>app/views</code> directory which holds the template files that make up the views associated with that controller. These files are used to display the view that results from each controller action.</p><p>Let's take a look at what Rails does by default when creating a new resource using the scaffold generator:</p><div class="code_container">
<pre class="brush: plain; gutter: false; toolbar: false">
$ rails generate scaffold article
[...]
invoke scaffold_controller
create app/controllers/articles_controller.rb
invoke erb
create app/views/articles
create app/views/articles/index.html.erb
create app/views/articles/edit.html.erb
create app/views/articles/show.html.erb
create app/views/articles/new.html.erb
create app/views/articles/_form.html.erb
[...]
</pre>
</div>
<p>There is a naming convention for views in Rails. Typically, the views share their name with the associated controller action, as you can see above.
For example, the index controller action of the <code>articles_controller.rb</code> will use the <code>index.html.erb</code> view file in the <code>app/views/articles</code> directory.
The complete HTML returned to the client is composed of a combination of this ERB file, a layout template that wraps it, and all the partials that the view may reference. Within this guide you will find more detailed documentation about each of these three components.</p><h3 id="templates-partials-and-layouts"><a class="anchorlink" href="#templates-partials-and-layouts">3 Templates, Partials, and Layouts</a></h3><p>As mentioned, the final HTML output is a composition of three Rails elements: <code>Templates</code>, <code>Partials</code> and <code>Layouts</code>.
Below is a brief overview of each of them.</p><h4 id="templates"><a class="anchorlink" href="#templates">3.1 Templates</a></h4><p>Action View templates can be written in several ways. If the template file has a <code>.erb</code> extension then it uses a mixture of ERB (Embedded Ruby) and HTML. If the template file has a <code>.builder</code> extension then the <code>Builder::XmlMarkup</code> library is used.</p><p>Rails supports multiple template systems and uses a file extension to distinguish amongst them. For example, an HTML file using the ERB template system will have <code>.html.erb</code> as a file extension.</p><h5 id="erb"><a class="anchorlink" href="#erb">3.1.1 ERB</a></h5><p>Within an ERB template, Ruby code can be included using both <code><% %></code> and <code><%= %></code> tags. The <code><% %></code> tags are used to execute Ruby code that does not return anything, such as conditions, loops, or blocks, and the <code><%= %></code> tags are used when you want output.</p><p>Consider the following loop for names:</p><div class="code_container">
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
<h1>Names of all the people</h1>
<% @people.each do |person| %>
Name: <%= person.name %><br>
<% end %>
</pre>
</div>
<p>The loop is set up using regular embedding tags (<code><% %></code>) and the name is inserted using the output embedding tags (<code><%= %></code>). Note that this is not just a usage suggestion: regular output functions such as <code>print</code> and <code>puts</code> won't be rendered to the view with ERB templates. So this would be wrong:</p><div class="code_container">
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
<%# WRONG %>
Hi, Mr. <% puts "Frodo" %>
</pre>
</div>
<p>To suppress leading and trailing whitespaces, you can use <code><%-</code> <code>-%></code> interchangeably with <code><%</code> and <code>%></code>.</p><h5 id="builder"><a class="anchorlink" href="#builder">3.1.2 Builder</a></h5><p>Builder templates are a more programmatic alternative to ERB. They are especially useful for generating XML content. An XmlMarkup object named <code>xml</code> is automatically made available to templates with a <code>.builder</code> extension.</p><p>Here are some basic examples:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
xml.em("emphasized")
xml.em { xml.b("emph & bold") }
xml.a("A Link", "href" => "http://rubyonrails.org")
xml.target("name" => "compile", "option" => "fast")
</pre>
</div>
<p>which would produce:</p><div class="code_container">
<pre class="brush: xml; gutter: false; toolbar: false">
<em>emphasized</em>
<em><b>emph &amp; bold</b></em>
<a href="http://rubyonrails.org">A link</a>
<target option="fast" name="compile" />
</pre>
</div>
<p>Any method with a block will be treated as an XML markup tag with nested markup in the block. For example, the following:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
xml.div {
xml.h1(@person.name)
xml.p(@person.bio)
}
</pre>
</div>
<p>would produce something like:</p><div class="code_container">
<pre class="brush: xml; gutter: false; toolbar: false">
<div>
<h1>David Heinemeier Hansson</h1>
<p>A product of Danish Design during the Winter of '79...</p>
</div>
</pre>
</div>
<p>Below is a full-length RSS example actually used on Basecamp:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
xml.rss("version" => "2.0", "xmlns:dc" => "http://purl.org/dc/elements/1.1/") do
xml.channel do
xml.title(@feed_title)
xml.link(@url)
xml.description "Basecamp: Recent items"
xml.language "en-us"
xml.ttl "40"
for item in @recent_items
xml.item do
xml.title(item_title(item))
xml.description(item_description(item)) if item_description(item)
xml.pubDate(item_pubDate(item))
xml.guid(@person.firm.account.url + @recent_items.url(item))
xml.link(@person.firm.account.url + @recent_items.url(item))
xml.tag!("dc:creator", item.author_name) if item_has_creator?(item)
end
end
end
end
</pre>
</div>
<h5 id="jbuilder"><a class="anchorlink" href="#jbuilder">3.1.3 Jbuilder</a></h5><p><a href="https://github.com/rails/jbuilder">Jbuilder</a> is a gem that's
maintained by the Rails team and included in the default Rails <code>Gemfile</code>.
It's similar to Builder, but is used to generate JSON, instead of XML.</p><p>If you don't have it, you can add the following to your <code>Gemfile</code>:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
gem 'jbuilder'
</pre>
</div>
<p>A Jbuilder object named <code>json</code> is automatically made available to templates with
a <code>.jbuilder</code> extension.</p><p>Here is a basic example:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
json.name("Alex")
json.email("[email protected]")
</pre>
</div>
<p>would produce:</p><div class="code_container">
<pre class="brush: plain; gutter: false; toolbar: false">
{
"name": "Alex",
"email": "[email protected]"
}
</pre>
</div>
<p>See the <a href="https://github.com/rails/jbuilder#jbuilder">Jbuilder documentation</a> for
more examples and information.</p><h5 id="template-caching"><a class="anchorlink" href="#template-caching">3.1.4 Template Caching</a></h5><p>By default, Rails will compile each template to a method in order to render it. When you alter a template, Rails will check the file's modification time and recompile it in development mode.</p><h4 id="partials"><a class="anchorlink" href="#partials">3.2 Partials</a></h4><p>Partial templates - usually just called "partials" - are another device for breaking the rendering process into more manageable chunks. With partials, you can extract pieces of code from your templates to separate files and also reuse them throughout your templates.</p><h5 id="naming-partials"><a class="anchorlink" href="#naming-partials">3.2.1 Naming Partials</a></h5><p>To render a partial as part of a view, you use the <code>render</code> method within the view:</p><div class="code_container">
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
<%= render "menu" %>
</pre>
</div>
<p>This will render a file named <code>_menu.html.erb</code> at that point within the view that is being rendered. Note the leading underscore character: partials are named with a leading underscore to distinguish them from regular views, even though they are referred to without the underscore. This holds true even when you're pulling in a partial from another folder:</p><div class="code_container">
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
<%= render "shared/menu" %>
</pre>
</div>
<p>That code will pull in the partial from <code>app/views/shared/_menu.html.erb</code>.</p><h5 id="using-partials-to-simplify-views"><a class="anchorlink" href="#using-partials-to-simplify-views">3.2.2 Using Partials to simplify Views</a></h5><p>One way to use partials is to treat them as the equivalent of subroutines; a way to move details out of a view so that you can grasp what's going on more easily. For example, you might have a view that looks like this:</p><div class="code_container">
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
<%= render "shared/ad_banner" %>
<h1>Products</h1>
<p>Here are a few of our fine products:</p>
<% @products.each do |product| %>
<%= render partial: "product", locals: { product: product } %>
<% end %>
<%= render "shared/footer" %>
</pre>
</div>
<p>Here, the <code>_ad_banner.html.erb</code> and <code>_footer.html.erb</code> partials could contain content that is shared among many pages in your application. You don't need to see the details of these sections when you're concentrating on a particular page.</p><h5 id="render-without-partial-and-locals-options"><a class="anchorlink" href="#render-without-partial-and-locals-options">3.2.3 <code>render</code> without <code>partial</code> and <code>locals</code> options</a></h5><p>In the above example, <code>render</code> takes 2 options: <code>partial</code> and <code>locals</code>. But if
these are the only options you want to pass, you can skip using these options.
For example, instead of:</p><div class="code_container">
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
<%= render partial: "product", locals: { product: @product } %>
</pre>
</div>
<p>You can also do:</p><div class="code_container">
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
<%= render "product", product: @product %>
</pre>
</div>
<h5 id="the-as-and-object-options"><a class="anchorlink" href="#the-as-and-object-options">3.2.4 The <code>as</code> and <code>object</code> options</a></h5><p>By default <code>ActionView::Partials::PartialRenderer</code> has its object in a local variable with the same name as the template. So, given:</p><div class="code_container">
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
<%= render partial: "product" %>
</pre>
</div>
<p>within <code>_product</code> partial we'll get <code>@product</code> in the local variable <code>product</code>,
as if we had written:</p><div class="code_container">
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
<%= render partial: "product", locals: { product: @product } %>
</pre>
</div>
<p>The <code>object</code> option can be used to directly specify which object is rendered into the partial; useful when the template's object is elsewhere (e.g. in a different instance variable or in a local variable).</p><p>For example, instead of:</p><div class="code_container">
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
<%= render partial: "product", locals: { product: @item } %>
</pre>
</div>
<p>we would do:</p><div class="code_container">
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
<%= render partial: "product", object: @item %>
</pre>
</div>
<p>With the <code>as</code> option we can specify a different name for the said local variable. For example, if we wanted it to be <code>item</code> instead of <code>product</code> we would do:</p><div class="code_container">
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
<%= render partial: "product", object: @item, as: "item" %>
</pre>
</div>
<p>This is equivalent to</p><div class="code_container">
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
<%= render partial: "product", locals: { item: @item } %>
</pre>
</div>
<h5 id="rendering-collections"><a class="anchorlink" href="#rendering-collections">3.2.5 Rendering Collections</a></h5><p>It is very common that a template will need to iterate over a collection and render a sub-template for each of the elements. This pattern has been implemented as a single method that accepts an array and renders a partial for each one of the elements in the array.</p><p>So this example for rendering all the products:</p><div class="code_container">
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
<% @products.each do |product| %>
<%= render partial: "product", locals: { product: product } %>
<% end %>
</pre>
</div>
<p>can be rewritten in a single line:</p><div class="code_container">
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
<%= render partial: "product", collection: @products %>
</pre>
</div>
<p>When a partial is called with a collection, the individual instances of the partial have access to the member of the collection being rendered via a variable named after the partial. In this case, the partial is <code>_product</code>, and within it you can refer to <code>product</code> to get the collection member that is being rendered.</p><p>You can use a shorthand syntax for rendering collections. Assuming <code>@products</code> is a collection of <code>Product</code> instances, you can simply write the following to produce the same result:</p><div class="code_container">
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
<%= render @products %>
</pre>
</div>
<p>Rails determines the name of the partial to use by looking at the model name in the collection, <code>Product</code> in this case. In fact, you can even render a collection made up of instances of different models using this shorthand, and Rails will choose the proper partial for each member of the collection.</p><h5 id="spacer-templates"><a class="anchorlink" href="#spacer-templates">3.2.6 Spacer Templates</a></h5><p>You can also specify a second partial to be rendered between instances of the main partial by using the <code>:spacer_template</code> option:</p><div class="code_container">
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
<%= render partial: @products, spacer_template: "product_ruler" %>
</pre>
</div>
<p>Rails will render the <code>_product_ruler</code> partial (with no data passed to it) between each pair of <code>_product</code> partials.</p><h4 id="layouts"><a class="anchorlink" href="#layouts">3.3 Layouts</a></h4><p>Layouts can be used to render a common view template around the results of Rails controller actions. Typically, a Rails application will have a couple of layouts that pages will be rendered within. For example, a site might have one layout for a logged in user and another for the marketing or sales side of the site. The logged in user layout might include top-level navigation that should be present across many controller actions. The sales layout for a SaaS app might include top-level navigation for things like "Pricing" and "Contact Us" pages. You would expect each layout to have a different look and feel. You can read about layouts in more detail in the <a href="layouts_and_rendering.html">Layouts and Rendering in Rails</a> guide.</p><h3 id="partial-layouts"><a class="anchorlink" href="#partial-layouts">4 Partial Layouts</a></h3><p>Partials can have their own layouts applied to them. These layouts are different from those applied to a controller action, but they work in a similar fashion.</p><p>Let's say we're displaying an article on a page which should be wrapped in a <code>div</code> for display purposes. Firstly, we'll create a new <code>Article</code>:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
Article.create(body: 'Partial Layouts are cool!')
</pre>
</div>
<p>In the <code>show</code> template, we'll render the <code>_article</code> partial wrapped in the <code>box</code> layout:</p><p><strong>articles/show.html.erb</strong></p><div class="code_container">
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
<%= render partial: 'article', layout: 'box', locals: { article: @article } %>
</pre>
</div>
<p>The <code>box</code> layout simply wraps the <code>_article</code> partial in a <code>div</code>:</p><p><strong>articles/_box.html.erb</strong></p><div class="code_container">
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
<div class='box'>
<%= yield %>
</div>
</pre>
</div>
<p>Note that the partial layout has access to the local <code>article</code> variable that was passed into the <code>render</code> call. However, unlike application-wide layouts, partial layouts still have the underscore prefix.</p><p>You can also render a block of code within a partial layout instead of calling <code>yield</code>. For example, if we didn't have the <code>_article</code> partial, we could do this instead:</p><p><strong>articles/show.html.erb</strong></p><div class="code_container">
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
<% render(layout: 'box', locals: { article: @article }) do %>
<div>
<p><%= article.body %></p>
</div>
<% end %>
</pre>
</div>
<p>Supposing we use the same <code>_box</code> partial from above, this would produce the same output as the previous example.</p><h3 id="view-paths"><a class="anchorlink" href="#view-paths">5 View Paths</a></h3><p>When rendering a response, the controller needs to resolve where the different
views are located. By default it only looks inside the <code>app/views</code> directory.</p><p>We can add other locations and give them a certain precedence when resolving
paths using the <code>prepend_view_path</code> and <code>append_view_path</code> methods.</p><h4 id="prepend-view-path"><a class="anchorlink" href="#prepend-view-path">5.1 Prepend view path</a></h4><p>This can be helpful for example, when we want to put views inside a different
directory for subdomains.</p><p>We can do this by using:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
prepend_view_path "app/views/#{request.subdomain}"
</pre>
</div>
<p>Then Action View will look first in this directory when resolving views.</p><h4 id="append-view-path"><a class="anchorlink" href="#append-view-path">5.2 Append view path</a></h4><p>Similarly, we can append paths:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
append_view_path "app/views/direct"
</pre>
</div>
<p>This will add <code>app/views/direct</code> to the end of the lookup paths.</p><h3 id="overview-of-helpers-provided-by-action-view"><a class="anchorlink" href="#overview-of-helpers-provided-by-action-view">6 Overview of helpers provided by Action View</a></h3><p>WIP: Not all the helpers are listed here. For a full list see the <a href="http://edgeapi.rubyonrails.org/classes/ActionView/Helpers.html">API documentation</a></p><p>The following is only a brief overview summary of the helpers available in Action View. It's recommended that you review the <a href="http://edgeapi.rubyonrails.org/classes/ActionView/Helpers.html">API Documentation</a>, which covers all of the helpers in more detail, but this should serve as a good starting point.</p><h4 id="assettaghelper"><a class="anchorlink" href="#assettaghelper">6.1 AssetTagHelper</a></h4><p>This module provides methods for generating HTML that links views to assets such as images, JavaScript files, stylesheets, and feeds.</p><p>By default, Rails links to these assets on the current host in the public folder, but you can direct Rails to link to assets from a dedicated assets server by setting <code>config.action_controller.asset_host</code> in the application configuration, typically in <code>config/environments/production.rb</code>. For example, let's say your asset host is <code>assets.example.com</code>:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
config.action_controller.asset_host = "assets.example.com"
image_tag("rails.png") # => <img src="http://assets.example.com/images/rails.png" />
</pre>
</div>
<h5 id="auto-discovery-link-tag"><a class="anchorlink" href="#auto-discovery-link-tag">6.1.1 auto_discovery_link_tag</a></h5><p>Returns a link tag that browsers and feed readers can use to auto-detect an RSS, Atom, or JSON feed.</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
auto_discovery_link_tag(:rss, "http://www.example.com/feed.rss", { title: "RSS Feed" }) # =>
<link rel="alternate" type="application/rss+xml" title="RSS Feed" href="http://www.example.com/feed.rss" />
</pre>
</div>
<h5 id="image-path"><a class="anchorlink" href="#image-path">6.1.2 image_path</a></h5><p>Computes the path to an image asset in the <code>app/assets/images</code> directory. Full paths from the document root will be passed through. Used internally by <code>image_tag</code> to build the image path.</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
image_path("edit.png") # => /assets/edit.png
</pre>
</div>
<p>Fingerprint will be added to the filename if config.assets.digest is set to true.</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
image_path("edit.png") # => /assets/edit-2d1a2db63fc738690021fedb5a65b68e.png
</pre>
</div>
<h5 id="image-url"><a class="anchorlink" href="#image-url">6.1.3 image_url</a></h5><p>Computes the URL to an image asset in the <code>app/assets/images</code> directory. This will call <code>image_path</code> internally and merge with your current host or your asset host.</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
image_url("edit.png") # => http://www.example.com/assets/edit.png
</pre>
</div>
<h5 id="image-tag"><a class="anchorlink" href="#image-tag">6.1.4 image_tag</a></h5><p>Returns an HTML image tag for the source. The source can be a full path or a file that exists in your <code>app/assets/images</code> directory.</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
image_tag("icon.png") # => <img src="/assets/icon.png" />
</pre>
</div>
<h5 id="javascript-include-tag"><a class="anchorlink" href="#javascript-include-tag">6.1.5 javascript_include_tag</a></h5><p>Returns an HTML script tag for each of the sources provided. You can pass in the filename (<code>.js</code> extension is optional) of JavaScript files that exist in your <code>app/assets/javascripts</code> directory for inclusion into the current page or you can pass the full path relative to your document root.</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
javascript_include_tag "common" # => <script src="/assets/common.js"></script>
</pre>
</div>
<h5 id="javascript-path"><a class="anchorlink" href="#javascript-path">6.1.6 javascript_path</a></h5><p>Computes the path to a JavaScript asset in the <code>app/assets/javascripts</code> directory. If the source filename has no extension, <code>.js</code> will be appended. Full paths from the document root will be passed through. Used internally by <code>javascript_include_tag</code> to build the script path.</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
javascript_path "common" # => /assets/common.js
</pre>
</div>
<h5 id="javascript-url"><a class="anchorlink" href="#javascript-url">6.1.7 javascript_url</a></h5><p>Computes the URL to a JavaScript asset in the <code>app/assets/javascripts</code> directory. This will call <code>javascript_path</code> internally and merge with your current host or your asset host.</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
javascript_url "common" # => http://www.example.com/assets/common.js
</pre>
</div>
<h5 id="stylesheet-link-tag"><a class="anchorlink" href="#stylesheet-link-tag">6.1.8 stylesheet_link_tag</a></h5><p>Returns a stylesheet link tag for the sources specified as arguments. If you don't specify an extension, <code>.css</code> will be appended automatically.</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
stylesheet_link_tag "application" # => <link href="/assets/application.css" media="screen" rel="stylesheet" />
</pre>
</div>
<h5 id="stylesheet-path"><a class="anchorlink" href="#stylesheet-path">6.1.9 stylesheet_path</a></h5><p>Computes the path to a stylesheet asset in the <code>app/assets/stylesheets</code> directory. If the source filename has no extension, <code>.css</code> will be appended. Full paths from the document root will be passed through. Used internally by <code>stylesheet_link_tag</code> to build the stylesheet path.</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
stylesheet_path "application" # => /assets/application.css
</pre>
</div>
<h5 id="stylesheet-url"><a class="anchorlink" href="#stylesheet-url">6.1.10 stylesheet_url</a></h5><p>Computes the URL to a stylesheet asset in the <code>app/assets/stylesheets</code> directory. This will call <code>stylesheet_path</code> internally and merge with your current host or your asset host.</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
stylesheet_url "application" # => http://www.example.com/assets/application.css
</pre>
</div>
<h4 id="atomfeedhelper"><a class="anchorlink" href="#atomfeedhelper">6.2 AtomFeedHelper</a></h4><h5 id="atom-feed"><a class="anchorlink" href="#atom-feed">6.2.1 atom_feed</a></h5><p>This helper makes building an Atom feed easy. Here's a full usage example:</p><p><strong>config/routes.rb</strong></p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
resources :articles
</pre>
</div>
<p><strong>app/controllers/articles_controller.rb</strong></p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
def index
@articles = Article.all
respond_to do |format|
format.html
format.atom
end
end
</pre>
</div>
<p><strong>app/views/articles/index.atom.builder</strong></p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
atom_feed do |feed|
feed.title("Articles Index")
feed.updated(@articles.first.created_at)
@articles.each do |article|
feed.entry(article) do |entry|
entry.title(article.title)
entry.content(article.body, type: 'html')
entry.author do |author|
author.name(article.author_name)
end
end
end
end
</pre>
</div>
<h4 id="benchmarkhelper"><a class="anchorlink" href="#benchmarkhelper">6.3 BenchmarkHelper</a></h4><h5 id="benchmark"><a class="anchorlink" href="#benchmark">6.3.1 benchmark</a></h5><p>Allows you to measure the execution time of a block in a template and records the result to the log. Wrap this block around expensive operations or possible bottlenecks to get a time reading for the operation.</p><div class="code_container">
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
<% benchmark "Process data files" do %>
<%= expensive_files_operation %>
<% end %>
</pre>
</div>
<p>This would add something like "Process data files (0.34523)" to the log, which you can then use to compare timings when optimizing your code.</p><h4 id="cachehelper"><a class="anchorlink" href="#cachehelper">6.4 CacheHelper</a></h4><h5 id="cache"><a class="anchorlink" href="#cache">6.4.1 cache</a></h5><p>A method for caching fragments of a view rather than an entire action or page. This technique is useful for caching pieces like menus, lists of news topics, static HTML fragments, and so on. This method takes a block that contains the content you wish to cache. See <code>AbstractController::Caching::Fragments</code> for more information.</p><div class="code_container">
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
<% cache do %>
<%= render "shared/footer" %>
<% end %>
</pre>
</div>
<h4 id="capturehelper"><a class="anchorlink" href="#capturehelper">6.5 CaptureHelper</a></h4><h5 id="capture"><a class="anchorlink" href="#capture">6.5.1 capture</a></h5><p>The <code>capture</code> method allows you to extract part of a template into a variable. You can then use this variable anywhere in your templates or layout.</p><div class="code_container">
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
<% @greeting = capture do %>
<p>Welcome! The date and time is <%= Time.now %></p>
<% end %>
</pre>
</div>
<p>The captured variable can then be used anywhere else.</p><div class="code_container">
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
<html>
<head>
<title>Welcome!</title>
</head>
<body>
<%= @greeting %>
</body>
</html>
</pre>
</div>
<h5 id="content-for"><a class="anchorlink" href="#content-for">6.5.2 content_for</a></h5><p>Calling <code>content_for</code> stores a block of markup in an identifier for later use. You can make subsequent calls to the stored content in other templates or the layout by passing the identifier as an argument to <code>yield</code>.</p><p>For example, let's say we have a standard application layout, but also a special page that requires certain JavaScript that the rest of the site doesn't need. We can use <code>content_for</code> to include this JavaScript on our special page without fattening up the rest of the site.</p><p><strong>app/views/layouts/application.html.erb</strong></p><div class="code_container">
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
<html>
<head>
<title>Welcome!</title>
<%= yield :special_script %>
</head>
<body>
<p>Welcome! The date and time is <%= Time.now %></p>
</body>
</html>
</pre>
</div>
<p><strong>app/views/articles/special.html.erb</strong></p><div class="code_container">
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
<p>This is a special page.</p>
<% content_for :special_script do %>
<script>alert('Hello!')</script>
<% end %>
</pre>
</div>
<h4 id="datehelper"><a class="anchorlink" href="#datehelper">6.6 DateHelper</a></h4><h5 id="date-select"><a class="anchorlink" href="#date-select">6.6.1 date_select</a></h5><p>Returns a set of select tags (one for year, month, and day) pre-selected for accessing a specified date-based attribute.</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
date_select("article", "published_on")
</pre>
</div>
<h5 id="datetime-select"><a class="anchorlink" href="#datetime-select">6.6.2 datetime_select</a></h5><p>Returns a set of select tags (one for year, month, day, hour, and minute) pre-selected for accessing a specified datetime-based attribute.</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
datetime_select("article", "published_on")
</pre>
</div>
<h5 id="distance-of-time-in-words"><a class="anchorlink" href="#distance-of-time-in-words">6.6.3 distance_of_time_in_words</a></h5><p>Reports the approximate distance in time between two Time or Date objects or integers as seconds. Set <code>include_seconds</code> to true if you want more detailed approximations.</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
distance_of_time_in_words(Time.now, Time.now + 15.seconds) # => less than a minute
distance_of_time_in_words(Time.now, Time.now + 15.seconds, include_seconds: true) # => less than 20 seconds
</pre>
</div>
<h5 id="select-date"><a class="anchorlink" href="#select-date">6.6.4 select_date</a></h5><p>Returns a set of HTML select-tags (one for year, month, and day) pre-selected with the <code>date</code> provided.</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
# Generates a date select that defaults to the date provided (six days after today)
select_date(Time.today + 6.days)
# Generates a date select that defaults to today (no specified date)
select_date()
</pre>
</div>
<h5 id="select-datetime"><a class="anchorlink" href="#select-datetime">6.6.5 select_datetime</a></h5><p>Returns a set of HTML select-tags (one for year, month, day, hour, and minute) pre-selected with the <code>datetime</code> provided.</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
# Generates a datetime select that defaults to the datetime provided (four days after today)
select_datetime(Time.now + 4.days)
# Generates a datetime select that defaults to today (no specified datetime)
select_datetime()
</pre>
</div>
<h5 id="select-day"><a class="anchorlink" href="#select-day">6.6.6 select_day</a></h5><p>Returns a select tag with options for each of the days 1 through 31 with the current day selected.</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
# Generates a select field for days that defaults to the day for the date provided
select_day(Time.today + 2.days)
# Generates a select field for days that defaults to the number given
select_day(5)
</pre>
</div>
<h5 id="select-hour"><a class="anchorlink" href="#select-hour">6.6.7 select_hour</a></h5><p>Returns a select tag with options for each of the hours 0 through 23 with the current hour selected.</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
# Generates a select field for hours that defaults to the hours for the time provided
select_hour(Time.now + 6.hours)
</pre>
</div>
<h5 id="select-minute"><a class="anchorlink" href="#select-minute">6.6.8 select_minute</a></h5><p>Returns a select tag with options for each of the minutes 0 through 59 with the current minute selected.</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
# Generates a select field for minutes that defaults to the minutes for the time provided.
select_minute(Time.now + 10.minutes)
</pre>
</div>
<h5 id="select-month"><a class="anchorlink" href="#select-month">6.6.9 select_month</a></h5><p>Returns a select tag with options for each of the months January through December with the current month selected.</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
# Generates a select field for months that defaults to the current month
select_month(Date.today)
</pre>
</div>
<h5 id="select-second"><a class="anchorlink" href="#select-second">6.6.10 select_second</a></h5><p>Returns a select tag with options for each of the seconds 0 through 59 with the current second selected.</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
# Generates a select field for seconds that defaults to the seconds for the time provided
select_second(Time.now + 16.seconds)
</pre>
</div>
<h5 id="select-time"><a class="anchorlink" href="#select-time">6.6.11 select_time</a></h5><p>Returns a set of HTML select-tags (one for hour and minute).</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
# Generates a time select that defaults to the time provided
select_time(Time.now)
</pre>
</div>
<h5 id="select-year"><a class="anchorlink" href="#select-year">6.6.12 select_year</a></h5><p>Returns a select tag with options for each of the five years on each side of the current, which is selected. The five year radius can be changed using the <code>:start_year</code> and <code>:end_year</code> keys in the <code>options</code>.</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
# Generates a select field for five years on either side of Date.today that defaults to the current year
select_year(Date.today)
# Generates a select field from 1900 to 2009 that defaults to the current year
select_year(Date.today, start_year: 1900, end_year: 2009)
</pre>
</div>
<h5 id="time-ago-in-words"><a class="anchorlink" href="#time-ago-in-words">6.6.13 time_ago_in_words</a></h5><p>Like <code>distance_of_time_in_words</code>, but where <code>to_time</code> is fixed to <code>Time.now</code>.</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
time_ago_in_words(3.minutes.from_now) # => 3 minutes
</pre>
</div>
<h5 id="time-select"><a class="anchorlink" href="#time-select">6.6.14 time_select</a></h5><p>Returns a set of select tags (one for hour, minute, and optionally second) pre-selected for accessing a specified time-based attribute. The selects are prepared for multi-parameter assignment to an Active Record object.</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
# Creates a time select tag that, when POSTed, will be stored in the order variable in the submitted attribute
time_select("order", "submitted")
</pre>
</div>
<h4 id="debughelper"><a class="anchorlink" href="#debughelper">6.7 DebugHelper</a></h4><p>Returns a <code>pre</code> tag that has object dumped by YAML. This creates a very readable way to inspect an object.</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
my_hash = { 'first' => 1, 'second' => 'two', 'third' => [1,2,3] }
debug(my_hash)
</pre>
</div>
<div class="code_container">
<pre class="brush: xml; gutter: false; toolbar: false">
<pre class='debug_dump'>---
first: 1
second: two
third:
- 1
- 2
- 3
</pre>
</pre>
</div>
<h4 id="formhelper"><a class="anchorlink" href="#formhelper">6.8 FormHelper</a></h4><p>Form helpers are designed to make working with models much easier compared to using just standard HTML elements by providing a set of methods for creating forms based on your models. This helper generates the HTML for forms, providing a method for each sort of input (e.g., text, password, select, and so on). When the form is submitted (i.e., when the user hits the submit button or form.submit is called via JavaScript), the form inputs will be bundled into the params object and passed back to the controller.</p><p>There are two types of form helpers: those that specifically work with model attributes and those that don't. This helper deals with those that work with model attributes; to see an example of form helpers that don't work with model attributes, check the <code>ActionView::Helpers::FormTagHelper</code> documentation.</p><p>The core method of this helper, <code>form_for</code>, gives you the ability to create a form for a model instance; for example, let's say that you have a model Person and want to create a new instance of it:</p><div class="code_container">
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
# Note: a @person variable will have been created in the controller (e.g. @person = Person.new)
<%= form_for @person, url: { action: "create" } do |f| %>
<%= f.text_field :first_name %>
<%= f.text_field :last_name %>
<%= submit_tag 'Create' %>
<% end %>
</pre>
</div>
<p>The HTML generated for this would be:</p><div class="code_container">
<pre class="brush: xml; gutter: false; toolbar: false">
<form class="new_person" id="new_person" action="/people" accept-charset="UTF-8" method="post">
<input name="utf8" type="hidden" value="&#x2713;" />
<input type="hidden" name="authenticity_token" value="lTuvBzs7ANygT0NFinXj98tfw3Emfm65wwYLbUvoWsK2pngccIQSUorM2C035M9dZswXgWTvKwFS8W5TVblpYw==" />
<input type="text" name="person[first_name]" id="person_first_name" />
<input type="text" name="person[last_name]" id="person_last_name" />
<input type="submit" name="commit" value="Create" data-disable-with="Create" />
</form>
</pre>
</div>
<p>The params object created when this form is submitted would look like:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
{"utf8" => "✓", "authenticity_token" => "lTuvBzs7ANygT0NFinXj98tfw3Emfm65wwYLbUvoWsK2pngccIQSUorM2C035M9dZswXgWTvKwFS8W5TVblpYw==", "person" => {"first_name" => "William", "last_name" => "Smith"}, "commit" => "Create", "controller" => "people", "action" => "create"}
</pre>
</div>
<p>The params hash has a nested person value, which can therefore be accessed with <code>params[:person]</code> in the controller.</p><h5 id="check-box"><a class="anchorlink" href="#check-box">6.8.1 check_box</a></h5><p>Returns a checkbox tag tailored for accessing a specified attribute.</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
# Let's say that @article.validated? is 1:
check_box("article", "validated")
# => <input type="checkbox" id="article_validated" name="article[validated]" value="1" />
# <input name="article[validated]" type="hidden" value="0" />
</pre>
</div>
<h5 id="fields-for"><a class="anchorlink" href="#fields-for">6.8.2 fields_for</a></h5><p>Creates a scope around a specific model object like <code>form_for</code>, but doesn't create the form tags themselves. This makes <code>fields_for</code> suitable for specifying additional model objects in the same form:</p><div class="code_container">
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
<%= form_for @person, url: { action: "update" } do |person_form| %>
First name: <%= person_form.text_field :first_name %>
Last name : <%= person_form.text_field :last_name %>
<%= fields_for @person.permission do |permission_fields| %>
Admin? : <%= permission_fields.check_box :admin %>
<% end %>
<% end %>
</pre>
</div>
<h5 id="file-field"><a class="anchorlink" href="#file-field">6.8.3 file_field</a></h5><p>Returns a file upload input tag tailored for accessing a specified attribute.</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
file_field(:user, :avatar)
# => <input type="file" id="user_avatar" name="user[avatar]" />
</pre>
</div>
<h5 id="form-for"><a class="anchorlink" href="#form-for">6.8.4 form_for</a></h5><p>Creates a form and a scope around a specific model object that is used as a base for questioning about values for the fields.</p><div class="code_container">
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
<%= form_for @article do |f| %>
<%= f.label :title, 'Title' %>:
<%= f.text_field :title %><br>
<%= f.label :body, 'Body' %>:
<%= f.text_area :body %><br>
<% end %>
</pre>
</div>
<h5 id="hidden-field"><a class="anchorlink" href="#hidden-field">6.8.5 hidden_field</a></h5><p>Returns a hidden input tag tailored for accessing a specified attribute.</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
hidden_field(:user, :token)
# => <input type="hidden" id="user_token" name="user[token]" value="#{@user.token}" />
</pre>
</div>
<h5 id="label"><a class="anchorlink" href="#label">6.8.6 label</a></h5><p>Returns a label tag tailored for labelling an input field for a specified attribute.</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
label(:article, :title)
# => <label for="article_title">Title</label>
</pre>
</div>
<h5 id="password-field"><a class="anchorlink" href="#password-field">6.8.7 password_field</a></h5><p>Returns an input tag of the "password" type tailored for accessing a specified attribute.</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
password_field(:login, :pass)
# => <input type="text" id="login_pass" name="login[pass]" value="#{@login.pass}" />
</pre>
</div>
<h5 id="radio-button"><a class="anchorlink" href="#radio-button">6.8.8 radio_button</a></h5><p>Returns a radio button tag for accessing a specified attribute.</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
# Let's say that @article.category returns "rails":
radio_button("article", "category", "rails")
radio_button("article", "category", "java")
# => <input type="radio" id="article_category_rails" name="article[category]" value="rails" checked="checked" />
# <input type="radio" id="article_category_java" name="article[category]" value="java" />
</pre>
</div>
<h5 id="text-area"><a class="anchorlink" href="#text-area">6.8.9 text_area</a></h5><p>Returns a textarea opening and closing tag set tailored for accessing a specified attribute.</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
text_area(:comment, :text, size: "20x30")
# => <textarea cols="20" rows="30" id="comment_text" name="comment[text]">
# #{@comment.text}
# </textarea>
</pre>
</div>
<h5 id="text-field"><a class="anchorlink" href="#text-field">6.8.10 text_field</a></h5><p>Returns an input tag of the "text" type tailored for accessing a specified attribute.</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
text_field(:article, :title)
# => <input type="text" id="article_title" name="article[title]" value="#{@article.title}" />
</pre>
</div>
<h5 id="email-field"><a class="anchorlink" href="#email-field">6.8.11 email_field</a></h5><p>Returns an input tag of the "email" type tailored for accessing a specified attribute.</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
email_field(:user, :email)
# => <input type="email" id="user_email" name="user[email]" value="#{@user.email}" />
</pre>
</div>
<h5 id="url-field"><a class="anchorlink" href="#url-field">6.8.12 url_field</a></h5><p>Returns an input tag of the "url" type tailored for accessing a specified attribute.</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
url_field(:user, :url)
# => <input type="url" id="user_url" name="user[url]" value="#{@user.url}" />
</pre>
</div>
<h4 id="formoptionshelper"><a class="anchorlink" href="#formoptionshelper">6.9 FormOptionsHelper</a></h4><p>Provides a number of methods for turning different kinds of containers into a set of option tags.</p><h5 id="collection-select"><a class="anchorlink" href="#collection-select">6.9.1 collection_select</a></h5><p>Returns <code>select</code> and <code>option</code> tags for the collection of existing return values of <code>method</code> for <code>object</code>'s class.</p><p>Example object structure for use with this method:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class Article < ApplicationRecord
belongs_to :author
end
class Author < ApplicationRecord
has_many :articles
def name_with_initial
"#{first_name.first}. #{last_name}"
end
end
</pre>
</div>
<p>Sample usage (selecting the associated Author for an instance of Article, <code>@article</code>):</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
collection_select(:article, :author_id, Author.all, :id, :name_with_initial, { prompt: true })
</pre>
</div>
<p>If <code>@article.author_id</code> is 1, this would return:</p><div class="code_container">
<pre class="brush: xml; gutter: false; toolbar: false">
<select name="article[author_id]">
<option value="">Please select</option>
<option value="1" selected="selected">D. Heinemeier Hansson</option>
<option value="2">D. Thomas</option>
<option value="3">M. Clark</option>
</select>
</pre>
</div>
<h5 id="collection-radio-buttons"><a class="anchorlink" href="#collection-radio-buttons">6.9.2 collection_radio_buttons</a></h5><p>Returns <code>radio_button</code> tags for the collection of existing return values of <code>method</code> for <code>object</code>'s class.</p><p>Example object structure for use with this method:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class Article < ApplicationRecord
belongs_to :author
end
class Author < ApplicationRecord
has_many :articles
def name_with_initial
"#{first_name.first}. #{last_name}"
end
end
</pre>
</div>
<p>Sample usage (selecting the associated Author for an instance of Article, <code>@article</code>):</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
collection_radio_buttons(:article, :author_id, Author.all, :id, :name_with_initial)
</pre>
</div>
<p>If <code>@article.author_id</code> is 1, this would return:</p><div class="code_container">
<pre class="brush: xml; gutter: false; toolbar: false">
<input id="article_author_id_1" name="article[author_id]" type="radio" value="1" checked="checked" />
<label for="article_author_id_1">D. Heinemeier Hansson</label>
<input id="article_author_id_2" name="article[author_id]" type="radio" value="2" />
<label for="article_author_id_2">D. Thomas</label>
<input id="article_author_id_3" name="article[author_id]" type="radio" value="3" />
<label for="article_author_id_3">M. Clark</label>
</pre>
</div>
<h5 id="collection-check-boxes"><a class="anchorlink" href="#collection-check-boxes">6.9.3 collection_check_boxes</a></h5><p>Returns <code>check_box</code> tags for the collection of existing return values of <code>method</code> for <code>object</code>'s class.</p><p>Example object structure for use with this method:</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class Article < ApplicationRecord
has_and_belongs_to_many :authors
end
class Author < ApplicationRecord
has_and_belongs_to_many :articles
def name_with_initial
"#{first_name.first}. #{last_name}"
end
end
</pre>
</div>
<p>Sample usage (selecting the associated Authors for an instance of Article, <code>@article</code>):</p><div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
collection_check_boxes(:article, :author_ids, Author.all, :id, :name_with_initial)
</pre>
</div>
<p>If <code>@article.author_ids</code> is [1], this would return:</p><div class="code_container">