railties 3.0.11 → 3.0.12.rc1
Sign up to get free protection for your applications and to get access to all the features.
- data/lib/rails/version.rb +2 -2
- metadata +305 -461
- data/guides/output/2_2_release_notes.html +0 -565
- data/guides/output/2_3_release_notes.html +0 -713
- data/guides/output/3_0_release_notes.html +0 -652
- data/guides/output/3_1_release_notes.html +0 -670
- data/guides/output/action_controller_overview.html +0 -925
- data/guides/output/action_mailer_basics.html +0 -658
- data/guides/output/action_view_overview.html +0 -1471
- data/guides/output/active_model_basics.html +0 -349
- data/guides/output/active_record_basics.html +0 -364
- data/guides/output/active_record_querying.html +0 -1272
- data/guides/output/active_record_validations_callbacks.html +0 -1292
- data/guides/output/active_resource_basics.html +0 -252
- data/guides/output/active_support_core_extensions.html +0 -3374
- data/guides/output/ajax_on_rails.html +0 -412
- data/guides/output/api_documentation_guidelines.html +0 -317
- data/guides/output/asset_pipeline.html +0 -691
- data/guides/output/association_basics.html +0 -1742
- data/guides/output/caching_with_rails.html +0 -533
- data/guides/output/command_line.html +0 -662
- data/guides/output/configuring.html +0 -811
- data/guides/output/contribute.html +0 -216
- data/guides/output/contributing_to_ruby_on_rails.html +0 -465
- data/guides/output/credits.html +0 -210
- data/guides/output/debugging_rails_applications.html +0 -791
- data/guides/output/engines.html +0 -673
- data/guides/output/form_helpers.html +0 -850
- data/guides/output/generators.html +0 -725
- data/guides/output/getting_started.html +0 -1980
- data/guides/output/i18n.html +0 -1054
- data/guides/output/images/belongs_to.png +0 -0
- data/guides/output/images/book_icon.gif +0 -0
- data/guides/output/images/bullet.gif +0 -0
- data/guides/output/images/challenge.png +0 -0
- data/guides/output/images/chapters_icon.gif +0 -0
- data/guides/output/images/check_bullet.gif +0 -0
- data/guides/output/images/credits_pic_blank.gif +0 -0
- data/guides/output/images/csrf.png +0 -0
- data/guides/output/images/customized_error_messages.png +0 -0
- data/guides/output/images/edge_badge.png +0 -0
- data/guides/output/images/error_messages.png +0 -0
- data/guides/output/images/feature_tile.gif +0 -0
- data/guides/output/images/footer_tile.gif +0 -0
- data/guides/output/images/fxn.png +0 -0
- data/guides/output/images/grey_bullet.gif +0 -0
- data/guides/output/images/habtm.png +0 -0
- data/guides/output/images/has_many.png +0 -0
- data/guides/output/images/has_many_through.png +0 -0
- data/guides/output/images/has_one.png +0 -0
- data/guides/output/images/has_one_through.png +0 -0
- data/guides/output/images/header_backdrop.png +0 -0
- data/guides/output/images/header_tile.gif +0 -0
- data/guides/output/images/i18n/demo_html_safe.png +0 -0
- data/guides/output/images/i18n/demo_localized_pirate.png +0 -0
- data/guides/output/images/i18n/demo_translated_en.png +0 -0
- data/guides/output/images/i18n/demo_translated_pirate.png +0 -0
- data/guides/output/images/i18n/demo_translation_missing.png +0 -0
- data/guides/output/images/i18n/demo_untranslated.png +0 -0
- data/guides/output/images/icons/README +0 -5
- data/guides/output/images/icons/callouts/1.png +0 -0
- data/guides/output/images/icons/callouts/10.png +0 -0
- data/guides/output/images/icons/callouts/11.png +0 -0
- data/guides/output/images/icons/callouts/12.png +0 -0
- data/guides/output/images/icons/callouts/13.png +0 -0
- data/guides/output/images/icons/callouts/14.png +0 -0
- data/guides/output/images/icons/callouts/15.png +0 -0
- data/guides/output/images/icons/callouts/2.png +0 -0
- data/guides/output/images/icons/callouts/3.png +0 -0
- data/guides/output/images/icons/callouts/4.png +0 -0
- data/guides/output/images/icons/callouts/5.png +0 -0
- data/guides/output/images/icons/callouts/6.png +0 -0
- data/guides/output/images/icons/callouts/7.png +0 -0
- data/guides/output/images/icons/callouts/8.png +0 -0
- data/guides/output/images/icons/callouts/9.png +0 -0
- data/guides/output/images/icons/caution.png +0 -0
- data/guides/output/images/icons/example.png +0 -0
- data/guides/output/images/icons/home.png +0 -0
- data/guides/output/images/icons/important.png +0 -0
- data/guides/output/images/icons/next.png +0 -0
- data/guides/output/images/icons/note.png +0 -0
- data/guides/output/images/icons/prev.png +0 -0
- data/guides/output/images/icons/tip.png +0 -0
- data/guides/output/images/icons/up.png +0 -0
- data/guides/output/images/icons/warning.png +0 -0
- data/guides/output/images/jaimeiniesta.jpg +0 -0
- data/guides/output/images/nav_arrow.gif +0 -0
- data/guides/output/images/polymorphic.png +0 -0
- data/guides/output/images/posts_index.png +0 -0
- data/guides/output/images/radar.png +0 -0
- data/guides/output/images/rails_guides_logo.gif +0 -0
- data/guides/output/images/rails_logo_remix.gif +0 -0
- data/guides/output/images/rails_welcome.png +0 -0
- data/guides/output/images/session_fixation.png +0 -0
- data/guides/output/images/tab_grey.gif +0 -0
- data/guides/output/images/tab_info.gif +0 -0
- data/guides/output/images/tab_note.gif +0 -0
- data/guides/output/images/tab_red.gif +0 -0
- data/guides/output/images/tab_yellow.gif +0 -0
- data/guides/output/images/tab_yellow.png +0 -0
- data/guides/output/images/validation_error_messages.png +0 -0
- data/guides/output/images/vijaydev.jpg +0 -0
- data/guides/output/index.html +0 -300
- data/guides/output/initialization.html +0 -1087
- data/guides/output/javascripts/guides.js +0 -7
- data/guides/output/javascripts/syntaxhighlighter/shBrushAS3.js +0 -59
- data/guides/output/javascripts/syntaxhighlighter/shBrushAppleScript.js +0 -75
- data/guides/output/javascripts/syntaxhighlighter/shBrushBash.js +0 -59
- data/guides/output/javascripts/syntaxhighlighter/shBrushCSharp.js +0 -65
- data/guides/output/javascripts/syntaxhighlighter/shBrushColdFusion.js +0 -100
- data/guides/output/javascripts/syntaxhighlighter/shBrushCpp.js +0 -97
- data/guides/output/javascripts/syntaxhighlighter/shBrushCss.js +0 -91
- data/guides/output/javascripts/syntaxhighlighter/shBrushDelphi.js +0 -55
- data/guides/output/javascripts/syntaxhighlighter/shBrushDiff.js +0 -41
- data/guides/output/javascripts/syntaxhighlighter/shBrushErlang.js +0 -52
- data/guides/output/javascripts/syntaxhighlighter/shBrushGroovy.js +0 -67
- data/guides/output/javascripts/syntaxhighlighter/shBrushJScript.js +0 -52
- data/guides/output/javascripts/syntaxhighlighter/shBrushJava.js +0 -57
- data/guides/output/javascripts/syntaxhighlighter/shBrushJavaFX.js +0 -58
- data/guides/output/javascripts/syntaxhighlighter/shBrushPerl.js +0 -72
- data/guides/output/javascripts/syntaxhighlighter/shBrushPhp.js +0 -88
- data/guides/output/javascripts/syntaxhighlighter/shBrushPlain.js +0 -33
- data/guides/output/javascripts/syntaxhighlighter/shBrushPowerShell.js +0 -74
- data/guides/output/javascripts/syntaxhighlighter/shBrushPython.js +0 -64
- data/guides/output/javascripts/syntaxhighlighter/shBrushRuby.js +0 -55
- data/guides/output/javascripts/syntaxhighlighter/shBrushSass.js +0 -94
- data/guides/output/javascripts/syntaxhighlighter/shBrushScala.js +0 -51
- data/guides/output/javascripts/syntaxhighlighter/shBrushSql.js +0 -66
- data/guides/output/javascripts/syntaxhighlighter/shBrushVb.js +0 -56
- data/guides/output/javascripts/syntaxhighlighter/shBrushXml.js +0 -69
- data/guides/output/javascripts/syntaxhighlighter/shCore.js +0 -17
- data/guides/output/layout.html +0 -312
- data/guides/output/layouts_and_rendering.html +0 -1257
- data/guides/output/migrations.html +0 -751
- data/guides/output/nested_model_forms.html +0 -350
- data/guides/output/performance_testing.html +0 -858
- data/guides/output/plugins.html +0 -590
- data/guides/output/rails_application_templates.html +0 -368
- data/guides/output/rails_on_rack.html +0 -408
- data/guides/output/routing.html +0 -1246
- data/guides/output/ruby_on_rails_guides_guidelines.html +0 -218
- data/guides/output/security.html +0 -968
- data/guides/output/stylesheets/fixes.css +0 -16
- data/guides/output/stylesheets/main.css +0 -445
- data/guides/output/stylesheets/print.css +0 -52
- data/guides/output/stylesheets/reset.css +0 -43
- data/guides/output/stylesheets/style.css +0 -13
- data/guides/output/stylesheets/syntaxhighlighter/shCore.css +0 -226
- data/guides/output/stylesheets/syntaxhighlighter/shCoreDefault.css +0 -328
- data/guides/output/stylesheets/syntaxhighlighter/shCoreDjango.css +0 -331
- data/guides/output/stylesheets/syntaxhighlighter/shCoreEclipse.css +0 -339
- data/guides/output/stylesheets/syntaxhighlighter/shCoreEmacs.css +0 -324
- data/guides/output/stylesheets/syntaxhighlighter/shCoreFadeToGrey.css +0 -328
- data/guides/output/stylesheets/syntaxhighlighter/shCoreMDUltra.css +0 -324
- data/guides/output/stylesheets/syntaxhighlighter/shCoreMidnight.css +0 -324
- data/guides/output/stylesheets/syntaxhighlighter/shCoreRDark.css +0 -324
- data/guides/output/stylesheets/syntaxhighlighter/shThemeDefault.css +0 -117
- data/guides/output/stylesheets/syntaxhighlighter/shThemeDjango.css +0 -120
- data/guides/output/stylesheets/syntaxhighlighter/shThemeEclipse.css +0 -128
- data/guides/output/stylesheets/syntaxhighlighter/shThemeEmacs.css +0 -113
- data/guides/output/stylesheets/syntaxhighlighter/shThemeFadeToGrey.css +0 -117
- data/guides/output/stylesheets/syntaxhighlighter/shThemeMDUltra.css +0 -113
- data/guides/output/stylesheets/syntaxhighlighter/shThemeMidnight.css +0 -113
- data/guides/output/stylesheets/syntaxhighlighter/shThemeRDark.css +0 -113
- data/guides/output/stylesheets/syntaxhighlighter/shThemeRailsGuides.css +0 -116
- data/guides/output/testing.html +0 -1182
@@ -1,850 +0,0 @@
|
|
1
|
-
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
|
2
|
-
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
|
3
|
-
|
4
|
-
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
|
5
|
-
<head>
|
6
|
-
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
|
7
|
-
|
8
|
-
<title>Ruby on Rails Guides: Rails Form helpers</title>
|
9
|
-
|
10
|
-
<link rel="stylesheet" type="text/css" href="stylesheets/style.css" />
|
11
|
-
<link rel="stylesheet" type="text/css" href="stylesheets/print.css" media="print" />
|
12
|
-
|
13
|
-
<link rel="stylesheet" type="text/css" href="stylesheets/syntaxhighlighter/shCore.css" />
|
14
|
-
<link rel="stylesheet" type="text/css" href="stylesheets/syntaxhighlighter/shThemeRailsGuides.css" />
|
15
|
-
|
16
|
-
<link rel="stylesheet" type="text/css" href="stylesheets/fixes.css" />
|
17
|
-
</head>
|
18
|
-
<body class="guide">
|
19
|
-
<div id="topNav">
|
20
|
-
<div class="wrapper">
|
21
|
-
<strong>More at <a href="http://rubyonrails.org/">rubyonrails.org:</a> </strong>
|
22
|
-
<a href="http://rubyonrails.org/">Overview</a> |
|
23
|
-
<a href="http://rubyonrails.org/download">Download</a> |
|
24
|
-
<a href="http://rubyonrails.org/deploy">Deploy</a> |
|
25
|
-
<a href="https://github.com/rails/rails">Code</a> |
|
26
|
-
<a href="http://rubyonrails.org/screencasts">Screencasts</a> |
|
27
|
-
<a href="http://rubyonrails.org/documentation">Documentation</a> |
|
28
|
-
<a href="http://rubyonrails.org/ecosystem">Ecosystem</a> |
|
29
|
-
<a href="http://rubyonrails.org/community">Community</a> |
|
30
|
-
<a href="http://weblog.rubyonrails.org/">Blog</a>
|
31
|
-
</div>
|
32
|
-
</div>
|
33
|
-
<div id="header">
|
34
|
-
<div class="wrapper clearfix">
|
35
|
-
<h1><a href="index.html" title="Return to home page">Guides.rubyonrails.org</a></h1>
|
36
|
-
<p class="hide"><a href="#mainCol">Skip navigation</a>.</p>
|
37
|
-
<ul class="nav">
|
38
|
-
<li><a href="index.html">Home</a></li>
|
39
|
-
<li class="index"><a href="index.html" onclick="guideMenu(); return false;" id="guidesMenu">Guides Index</a>
|
40
|
-
<div id="guides" class="clearfix" style="display: none;">
|
41
|
-
<hr />
|
42
|
-
<dl class="L">
|
43
|
-
<dt>Start Here</dt>
|
44
|
-
<dd><a href="getting_started.html">Getting Started with Rails</a></dd>
|
45
|
-
<dt>Models</dt>
|
46
|
-
<dd><a href="migrations.html">Rails Database Migrations</a></dd>
|
47
|
-
<dd><a href="active_record_validations_callbacks.html">Active Record Validations and Callbacks</a></dd>
|
48
|
-
<dd><a href="association_basics.html">Active Record Associations</a></dd>
|
49
|
-
<dd><a href="active_record_querying.html">Active Record Query Interface</a></dd>
|
50
|
-
<dt>Views</dt>
|
51
|
-
<dd><a href="layouts_and_rendering.html">Layouts and Rendering in Rails</a></dd>
|
52
|
-
<dd><a href="form_helpers.html">Action View Form Helpers</a></dd>
|
53
|
-
<dt>Controllers</dt>
|
54
|
-
<dd><a href="action_controller_overview.html">Action Controller Overview</a></dd>
|
55
|
-
<dd><a href="routing.html">Rails Routing from the Outside In</a></dd>
|
56
|
-
</dl>
|
57
|
-
<dl class="R">
|
58
|
-
<dt>Digging Deeper</dt>
|
59
|
-
<dd><a href="active_support_core_extensions.html">Active Support Core Extensions</a></dd>
|
60
|
-
<dd><a href="i18n.html">Rails Internationalization API</a></dd>
|
61
|
-
<dd><a href="action_mailer_basics.html">Action Mailer Basics</a></dd>
|
62
|
-
<dd><a href="testing.html">Testing Rails Applications</a></dd>
|
63
|
-
<dd><a href="security.html">Securing Rails Applications</a></dd>
|
64
|
-
<dd><a href="debugging_rails_applications.html">Debugging Rails Applications</a></dd>
|
65
|
-
<dd><a href="performance_testing.html">Performance Testing Rails Applications</a></dd>
|
66
|
-
<dd><a href="configuring.html">Configuring Rails Applications</a></dd>
|
67
|
-
<dd><a href="command_line.html">Rails Command Line Tools and Rake Tasks</a></dd>
|
68
|
-
<dd><a href="caching_with_rails.html">Caching with Rails</a></dd>
|
69
|
-
<dd><a href="asset_pipeline.html">Asset Pipeline</a></dd>
|
70
|
-
|
71
|
-
<dt>Extending Rails</dt>
|
72
|
-
<dd><a href="plugins.html">The Basics of Creating Rails Plugins</a></dd>
|
73
|
-
<dd><a href="rails_on_rack.html">Rails on Rack</a></dd>
|
74
|
-
<dd><a href="generators.html">Creating and Customizing Rails Generators</a></dd>
|
75
|
-
|
76
|
-
<dt>Contributing to Ruby on Rails</dt>
|
77
|
-
<dd><a href="contributing_to_ruby_on_rails.html">Contributing to Ruby on Rails</a></dd>
|
78
|
-
<dd><a href="api_documentation_guidelines.html">API Documentation Guidelines</a></dd>
|
79
|
-
<dd><a href="ruby_on_rails_guides_guidelines.html">Ruby on Rails Guides Guidelines</a></dd>
|
80
|
-
|
81
|
-
<dt>Release Notes</dt>
|
82
|
-
<dd><a href="3_1_release_notes.html">Ruby on Rails 3.1 Release Notes</a></dd>
|
83
|
-
<dd><a href="3_0_release_notes.html">Ruby on Rails 3.0 Release Notes</a></dd>
|
84
|
-
<dd><a href="2_3_release_notes.html">Ruby on Rails 2.3 Release Notes</a></dd>
|
85
|
-
<dd><a href="2_2_release_notes.html">Ruby on Rails 2.2 Release Notes</a></dd>
|
86
|
-
</dl>
|
87
|
-
</div>
|
88
|
-
</li>
|
89
|
-
<li><a href="contributing_to_ruby_on_rails.html">Contribute</a></li>
|
90
|
-
<li><a href="credits.html">Credits</a></li>
|
91
|
-
</ul>
|
92
|
-
</div>
|
93
|
-
</div>
|
94
|
-
<hr class="hide" />
|
95
|
-
|
96
|
-
<div id="feature">
|
97
|
-
<div class="wrapper">
|
98
|
-
<h2>Rails Form helpers</h2>
|
99
|
-
<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>
|
100
|
-
<p>In this guide you will:</p>
|
101
|
-
<ul>
|
102
|
-
<li>Create search forms and similar kind of generic forms not representing any specific model in your application</li>
|
103
|
-
<li>Make model-centric forms for creation and editing of specific database records</li>
|
104
|
-
<li>Generate select boxes from multiple types of data</li>
|
105
|
-
<li>Understand the date and time helpers Rails provides</li>
|
106
|
-
<li>Learn what makes a file upload form different</li>
|
107
|
-
<li>Learn some cases of building forms to external resources</li>
|
108
|
-
<li>Find out where to look for complex forms</li>
|
109
|
-
</ul>
|
110
|
-
|
111
|
-
<div id="subCol">
|
112
|
-
<h3 class="chapter"><img src="images/chapters_icon.gif" alt="" />Chapters</h3>
|
113
|
-
<ol class="chapters">
|
114
|
-
<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="#forms-to-external-resources">Forms to external resources</a></li><li><a href="#building-complex-forms">Building Complex Forms</a></li></ol></div>
|
115
|
-
</div>
|
116
|
-
</div>
|
117
|
-
|
118
|
-
<div id="container">
|
119
|
-
<div class="wrapper">
|
120
|
-
<div id="mainCol">
|
121
|
-
<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>
|
122
|
-
<h3 id="dealing-with-basic-forms">1 Dealing with Basic Forms</h3>
|
123
|
-
<p>The most basic form helper is <tt>form_tag</tt>.</p>
|
124
|
-
<div class="code_container">
|
125
|
-
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
|
126
|
-
<%= form_tag do %>
|
127
|
-
Form contents
|
128
|
-
<% end %>
|
129
|
-
</pre>
|
130
|
-
</div>
|
131
|
-
<p>When called without arguments like this, it creates a <tt><form></tt> tag which, when submitted, will <span class="caps">POST</span> to the current page. For instance, assuming the current page is <tt>/home/index</tt>, the generated <span class="caps">HTML</span> will look like this (some line breaks added for readability):</p>
|
132
|
-
<div class="code_container">
|
133
|
-
<pre class="brush: xml; gutter: false; toolbar: false">
|
134
|
-
<form accept-charset="UTF-8" action="/home/index" method="post">
|
135
|
-
<div style="margin:0;padding:0">
|
136
|
-
<input name="utf8" type="hidden" value="&#x2713;" />
|
137
|
-
<input name="authenticity_token" type="hidden" value="f755bb0ed134b76c432144748a6d4b7a7ddf2b71" />
|
138
|
-
</div>
|
139
|
-
Form contents
|
140
|
-
</form>
|
141
|
-
</pre>
|
142
|
-
</div>
|
143
|
-
<p>Now, you’ll notice that the <span class="caps">HTML</span> contains something extra: a <tt>div</tt> element with two hidden input elements inside. This div is important, because the form cannot be successfully submitted without it. 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 their actions are “<span class="caps">GET</span>” or “<span class="caps">POST</span>”. The 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 non-<span class="caps">GET</span> form (provided that this security feature is enabled). You can read more about this in the <a href="./security.html#_cross_site_reference_forgery_csrf">Security Guide</a>.</p>
|
144
|
-
<div class="note"><p>Throughout this guide, the <tt>div</tt> with the hidden input elements will be excluded from code samples for brevity.</p></div>
|
145
|
-
<h4 id="a-generic-search-form">1.1 A Generic Search Form</h4>
|
146
|
-
<p>One of the most basic forms you see on the web is a search form. This form contains:</p>
|
147
|
-
<ol>
|
148
|
-
<li>a form element with “<span class="caps">GET</span>” method,</li>
|
149
|
-
<li>a label for the input,</li>
|
150
|
-
<li>a text input element, and</li>
|
151
|
-
<li>a submit element.</li>
|
152
|
-
</ol>
|
153
|
-
<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. Like this:</p>
|
154
|
-
<div class="code_container">
|
155
|
-
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
|
156
|
-
<%= form_tag("/search", :method => "get") do %>
|
157
|
-
<%= label_tag(:q, "Search for:") %>
|
158
|
-
<%= text_field_tag(:q) %>
|
159
|
-
<%= submit_tag("Search") %>
|
160
|
-
<% end %>
|
161
|
-
</pre>
|
162
|
-
</div>
|
163
|
-
<p>This will generate the following <span class="caps">HTML</span>:</p>
|
164
|
-
<div class="code_container">
|
165
|
-
<pre class="brush: xml; gutter: false; toolbar: false">
|
166
|
-
<form accept-charset="UTF-8" action="/search" method="get">
|
167
|
-
<label for="q">Search for:</label>
|
168
|
-
<input id="q" name="q" type="text" />
|
169
|
-
<input name="commit" type="submit" value="Search" />
|
170
|
-
</form>
|
171
|
-
</pre>
|
172
|
-
</div>
|
173
|
-
<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>
|
174
|
-
<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>
|
175
|
-
<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>
|
176
|
-
<h4 id="multiple-hashes-in-form-helper-calls">1.2 Multiple Hashes in Form Helper Calls</h4>
|
177
|
-
<p>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>
|
178
|
-
<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 recognizable by Rails’ routing mechanism, which will turn the hash into a valid <span class="caps">URL</span>. However, since both arguments to <tt>form_tag</tt> are hashes, you can easily run into a problem if you would like to specify both. For instance, let’s say you write this:</p>
|
179
|
-
<div class="code_container">
|
180
|
-
<pre class="brush: ruby; gutter: false; toolbar: false">
|
181
|
-
form_tag(:controller => "people", :action => "search", :method => "get", :class => "nifty_form")
|
182
|
-
# => '<form accept-charset="UTF-8" action="/people/search?method=get&class=nifty_form" method="post">'
|
183
|
-
</pre>
|
184
|
-
</div>
|
185
|
-
<p>Here, <tt>method</tt> and <tt>class</tt> are appended to the query string of the generated <span class="caps">URL</span> because you even though you mean to write two hashes, you really only specified one. So you need to tell Ruby which is which by delimiting the first hash (or both) with curly brackets. This will generate the <span class="caps">HTML</span> you expect:</p>
|
186
|
-
<div class="code_container">
|
187
|
-
<pre class="brush: ruby; gutter: false; toolbar: false">
|
188
|
-
form_tag({:controller => "people", :action => "search"}, :method => "get", :class => "nifty_form")
|
189
|
-
# => '<form accept-charset="UTF-8" action="/people/search" method="get" class="nifty_form">'
|
190
|
-
</pre>
|
191
|
-
</div>
|
192
|
-
<h4 id="helpers-for-generating-form-elements">1.3 Helpers for Generating Form Elements</h4>
|
193
|
-
<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. When the form is submitted, the name will be passed along with the form data, and will make its way to the <tt>params</tt> hash in the controller with the value entered by the user for that field. For example, if the form contains <tt><%= text_field_tag(:query) %></tt>, then you would be able to get the value of this field in the controller with <tt>params[:query]</tt>.</p>
|
194
|
-
<p>When naming inputs, Rails uses certain conventions that make it possible to submit parameters with non-scalar values such as arrays or hashes, which will also be accessible in <tt>params</tt>. You can read more about them in <a href="#understanding-parameter-naming-conventions">chapter 7 of this guide</a>. 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>
|
195
|
-
<h5 id="checkboxes">1.3.1 Checkboxes</h5>
|
196
|
-
<p>Checkboxes are form controls that give the user a set of options they can enable or disable:</p>
|
197
|
-
<div class="code_container">
|
198
|
-
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
|
199
|
-
<%= check_box_tag(:pet_dog) %>
|
200
|
-
<%= label_tag(:pet_dog, "I own a dog") %>
|
201
|
-
<%= check_box_tag(:pet_cat) %>
|
202
|
-
<%= label_tag(:pet_cat, "I own a cat") %>
|
203
|
-
</pre>
|
204
|
-
</div>
|
205
|
-
<p>This generates the following:</p>
|
206
|
-
<div class="code_container">
|
207
|
-
<pre class="brush: xml; gutter: false; toolbar: false">
|
208
|
-
<input id="pet_dog" name="pet_dog" type="checkbox" value="1" />
|
209
|
-
<label for="pet_dog">I own a dog</label>
|
210
|
-
<input id="pet_cat" name="pet_cat" type="checkbox" value="1" />
|
211
|
-
<label for="pet_cat">I own a cat</label>
|
212
|
-
</pre>
|
213
|
-
</div>
|
214
|
-
<p>The first parameter to <tt>check_box_tag</tt>, of course, is the name of the input. The second parameter, naturally, is the value of the input. This value will be included in the form data (and be present in <tt>params</tt>) when the checkbox is checked.</p>
|
215
|
-
<h5 id="radio-buttons">1.3.2 Radio Buttons</h5>
|
216
|
-
<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>
|
217
|
-
<div class="code_container">
|
218
|
-
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
|
219
|
-
<%= radio_button_tag(:age, "child") %>
|
220
|
-
<%= label_tag(:age_child, "I am younger than 21") %>
|
221
|
-
<%= radio_button_tag(:age, "adult") %>
|
222
|
-
<%= label_tag(:age_adult, "I'm over 21") %>
|
223
|
-
</pre>
|
224
|
-
</div>
|
225
|
-
<p>Output:</p>
|
226
|
-
<div class="code_container">
|
227
|
-
<pre class="brush: xml; gutter: false; toolbar: false">
|
228
|
-
<input id="age_child" name="age" type="radio" value="child" />
|
229
|
-
<label for="age_child">I am younger than 21</label>
|
230
|
-
<input id="age_adult" name="age" type="radio" value="adult" />
|
231
|
-
<label for="age_adult">I'm over 21</label>
|
232
|
-
</pre>
|
233
|
-
</div>
|
234
|
-
<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>
|
235
|
-
<div class="note"><p>Always use labels for checkbox and radio buttons. They associate text with a specific option and make it easier for users to click the inputs by expanding the clickable region.</p></div>
|
236
|
-
<h4 id="other-helpers-of-interest">1.4 Other Helpers of Interest</h4>
|
237
|
-
<p>Other form controls worth mentioning are textareas, password fields, hidden fields, search fields, telephone fields, <span class="caps">URL</span> fields and email fields:</p>
|
238
|
-
<div class="code_container">
|
239
|
-
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
|
240
|
-
<%= text_area_tag(:message, "Hi, nice site", :size => "24x6") %>
|
241
|
-
<%= password_field_tag(:password) %>
|
242
|
-
<%= hidden_field_tag(:parent_id, "5") %>
|
243
|
-
<%= search_field(:user, :name) %>
|
244
|
-
<%= telephone_field(:user, :phone) %>
|
245
|
-
<%= url_field(:user, :homepage) %>
|
246
|
-
<%= email_field(:user, :address) %>
|
247
|
-
</pre>
|
248
|
-
</div>
|
249
|
-
<p>Output:</p>
|
250
|
-
<div class="code_container">
|
251
|
-
<pre class="brush: xml; gutter: false; toolbar: false">
|
252
|
-
<textarea id="message" name="message" cols="24" rows="6">Hi, nice site</textarea>
|
253
|
-
<input id="password" name="password" type="password" />
|
254
|
-
<input id="parent_id" name="parent_id" type="hidden" value="5" />
|
255
|
-
<input id="user_name" name="user[name]" size="30" type="search" />
|
256
|
-
<input id="user_phone" name="user[phone]" size="30" type="tel" />
|
257
|
-
<input id="user_homepage" size="30" name="user[homepage]" type="url" />
|
258
|
-
<input id="user_address" size="30" name="user[address]" type="email" />
|
259
|
-
</pre>
|
260
|
-
</div>
|
261
|
-
<p>Hidden inputs are not shown to the user but instead hold data like any textual input. Values inside them can be changed with JavaScript.</p>
|
262
|
-
<div class="warning"><p>The search, telephone, <span class="caps">URL</span>, and email inputs are HTML5 controls. If you require your app to have a consistent experience in older browsers, you will need an HTML5 polyfill (provided by <span class="caps">CSS</span> and/or JavaScript). There is definitely <a href="https://github.com/Modernizr/Modernizr/wiki/HTML5-Cross-Browser-Polyfills">no shortage of solutions for this</a>, although a couple of popular tools at the moment are <a href="http://www.modernizr.com/">Modernizr</a> and <a href="http://yepnopejs.com/">yepnope</a>, which provide a simple way to add functionality based on the presence of detected HTML5 features.</p></div>
|
263
|
-
<div class="info"><p>If you’re using password input fields (for any purpose), you might want to configure your application to prevent those parameters from being logged. You can learn about this in the <a href="security.html#logging">Security Guide</a>.</p></div>
|
264
|
-
<h3 id="dealing-with-model-objects">2 Dealing with Model Objects</h3>
|
265
|
-
<h4 id="model-object-helpers">2.1 Model Object Helpers</h4>
|
266
|
-
<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>
|
267
|
-
<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>
|
268
|
-
<div class="code_container">
|
269
|
-
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
|
270
|
-
<%= text_field(:person, :name) %>
|
271
|
-
</pre>
|
272
|
-
</div>
|
273
|
-
<p>will produce output similar to</p>
|
274
|
-
<div class="code_container">
|
275
|
-
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
|
276
|
-
<input id="person_name" name="person[name]" type="text" value="Henry"/>
|
277
|
-
</pre>
|
278
|
-
</div>
|
279
|
-
<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>
|
280
|
-
<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>
|
281
|
-
<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>
|
282
|
-
<h4 id="binding-a-form-to-an-object">2.2 Binding a Form to an Object</h4>
|
283
|
-
<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>
|
284
|
-
<p>Assume we have a controller for dealing with articles <tt>app/controllers/articles_controller.rb</tt>:</p>
|
285
|
-
<div class="code_container">
|
286
|
-
<pre class="brush: ruby; gutter: false; toolbar: false">
|
287
|
-
def new
|
288
|
-
@article = Article.new
|
289
|
-
end
|
290
|
-
</pre>
|
291
|
-
</div>
|
292
|
-
<p>The corresponding view <tt>app/views/articles/new.html.erb</tt> using <tt>form_for</tt> looks like this:</p>
|
293
|
-
<div class="code_container">
|
294
|
-
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
|
295
|
-
<%= form_for @article, :url => { :action => "create" }, :html => {:class => "nifty_form"} do |f| %>
|
296
|
-
<%= f.text_field :title %>
|
297
|
-
<%= f.text_area :body, :size => "60x12" %>
|
298
|
-
<%= f.submit "Create" %>
|
299
|
-
<% end %>
|
300
|
-
</pre>
|
301
|
-
</div>
|
302
|
-
<p>There are a few things to note here:</p>
|
303
|
-
<ol>
|
304
|
-
<li><tt>@article</tt> is the actual object being edited.</li>
|
305
|
-
<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>
|
306
|
-
<li>The <tt>form_for</tt> method yields a <strong>form builder</strong> object (the <tt>f</tt> variable).</li>
|
307
|
-
<li>Methods to create form controls are called <strong>on</strong> the form builder object <tt>f</tt></li>
|
308
|
-
</ol>
|
309
|
-
<p>The resulting <span class="caps">HTML</span> is:</p>
|
310
|
-
<div class="code_container">
|
311
|
-
<pre class="brush: xml; gutter: false; toolbar: false">
|
312
|
-
<form accept-charset="UTF-8" action="/articles/create" method="post" class="nifty_form">
|
313
|
-
<input id="article_title" name="article[title]" size="30" type="text" />
|
314
|
-
<textarea id="article_body" name="article[body]" cols="60" rows="12"></textarea>
|
315
|
-
<input name="commit" type="submit" value="Create" />
|
316
|
-
</form>
|
317
|
-
</pre>
|
318
|
-
</div>
|
319
|
-
<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>
|
320
|
-
<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>
|
321
|
-
<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>
|
322
|
-
<div class="code_container">
|
323
|
-
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
|
324
|
-
<%= form_for @person, :url => { :action => "create" } do |person_form| %>
|
325
|
-
<%= person_form.text_field :name %>
|
326
|
-
<%= fields_for @person.contact_detail do |contact_details_form| %>
|
327
|
-
<%= contact_details_form.text_field :phone_number %>
|
328
|
-
<% end %>
|
329
|
-
<% end %>
|
330
|
-
</pre>
|
331
|
-
</div>
|
332
|
-
<p>which produces the following output:</p>
|
333
|
-
<div class="code_container">
|
334
|
-
<pre class="brush: xml; gutter: false; toolbar: false">
|
335
|
-
<form accept-charset="UTF-8" action="/people/create" class="new_person" id="new_person" method="post">
|
336
|
-
<input id="person_name" name="person[name]" size="30" type="text" />
|
337
|
-
<input id="contact_detail_phone_number" name="contact_detail[phone_number]" size="30" type="text" />
|
338
|
-
</form>
|
339
|
-
</pre>
|
340
|
-
</div>
|
341
|
-
<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>
|
342
|
-
<h4 id="relying-on-record-identification">2.3 Relying on Record Identification</h4>
|
343
|
-
<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>
|
344
|
-
<div class="code_container">
|
345
|
-
<pre class="brush: ruby; gutter: false; toolbar: false">
|
346
|
-
resources :articles
|
347
|
-
</pre>
|
348
|
-
</div>
|
349
|
-
<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>
|
350
|
-
<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>
|
351
|
-
<div class="code_container">
|
352
|
-
<pre class="brush: ruby; gutter: false; toolbar: false">
|
353
|
-
## Creating a new article
|
354
|
-
# long-style:
|
355
|
-
form_for(@article, :url => articles_path)
|
356
|
-
# same thing, short-style (record identification gets used):
|
357
|
-
form_for(@article)
|
358
|
-
|
359
|
-
## Editing an existing article
|
360
|
-
# long-style:
|
361
|
-
form_for(@article, :url => article_path(@article), :html => { :method => "put" })
|
362
|
-
# short-style:
|
363
|
-
form_for(@article)
|
364
|
-
</pre>
|
365
|
-
</div>
|
366
|
-
<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>
|
367
|
-
<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>
|
368
|
-
<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>
|
369
|
-
<h5 id="dealing-with-namespaces">2.3.1 Dealing with Namespaces</h5>
|
370
|
-
<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>
|
371
|
-
<div class="code_container">
|
372
|
-
<pre class="brush: ruby; gutter: false; toolbar: false">
|
373
|
-
form_for [:admin, @article]
|
374
|
-
</pre>
|
375
|
-
</div>
|
376
|
-
<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>
|
377
|
-
<div class="code_container">
|
378
|
-
<pre class="brush: ruby; gutter: false; toolbar: false">
|
379
|
-
form_for [:admin, :management, @article]
|
380
|
-
</pre>
|
381
|
-
</div>
|
382
|
-
<p>For more information on Rails’ routing system and the associated conventions, please see the <a href="routing.html">routing guide</a>.</p>
|
383
|
-
<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>
|
384
|
-
<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>
|
385
|
-
<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>
|
386
|
-
<div class="code_container">
|
387
|
-
<pre class="brush: ruby; gutter: false; toolbar: false">
|
388
|
-
form_tag(search_path, :method => "put")
|
389
|
-
</pre>
|
390
|
-
</div>
|
391
|
-
<p>output:</p>
|
392
|
-
<div class="code_container">
|
393
|
-
<pre class="brush: xml; gutter: false; toolbar: false">
|
394
|
-
<form accept-charset="UTF-8" action="/search" method="post">
|
395
|
-
<div style="margin:0;padding:0">
|
396
|
-
<input name="_method" type="hidden" value="put" />
|
397
|
-
<input name="utf8" type="hidden" value="&#x2713;" />
|
398
|
-
<input name="authenticity_token" type="hidden" value="f755bb0ed134b76c432144748a6d4b7a7ddf2b71" />
|
399
|
-
</div>
|
400
|
-
...
|
401
|
-
</pre>
|
402
|
-
</div>
|
403
|
-
<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>
|
404
|
-
<h3 id="making-select-boxes-with-ease">3 Making Select Boxes with Ease</h3>
|
405
|
-
<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>
|
406
|
-
<p>Here is what the markup might look like:</p>
|
407
|
-
<div class="code_container">
|
408
|
-
<pre class="brush: xml; gutter: false; toolbar: false">
|
409
|
-
<select name="city_id" id="city_id">
|
410
|
-
<option value="1">Lisbon</option>
|
411
|
-
<option value="2">Madrid</option>
|
412
|
-
...
|
413
|
-
<option value="12">Berlin</option>
|
414
|
-
</select>
|
415
|
-
</pre>
|
416
|
-
</div>
|
417
|
-
<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>
|
418
|
-
<h4 id="the-select-and-option-tags">3.1 The Select and Option Tags</h4>
|
419
|
-
<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>
|
420
|
-
<div class="code_container">
|
421
|
-
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
|
422
|
-
<%= select_tag(:city_id, '<option value="1">Lisbon</option>...') %>
|
423
|
-
</pre>
|
424
|
-
</div>
|
425
|
-
<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>
|
426
|
-
<div class="code_container">
|
427
|
-
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
|
428
|
-
<%= options_for_select([['Lisbon', 1], ['Madrid', 2], ...]) %>
|
429
|
-
|
430
|
-
output:
|
431
|
-
|
432
|
-
<option value="1">Lisbon</option>
|
433
|
-
<option value="2">Madrid</option>
|
434
|
-
...
|
435
|
-
</pre>
|
436
|
-
</div>
|
437
|
-
<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>
|
438
|
-
<p>Knowing this, you can combine <tt>select_tag</tt> and <tt>options_for_select</tt> to achieve the desired, complete markup:</p>
|
439
|
-
<div class="code_container">
|
440
|
-
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
|
441
|
-
<%= select_tag(:city_id, options_for_select(...)) %>
|
442
|
-
</pre>
|
443
|
-
</div>
|
444
|
-
<p><tt>options_for_select</tt> allows you to pre-select an option by passing its value.</p>
|
445
|
-
<div class="code_container">
|
446
|
-
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
|
447
|
-
<%= options_for_select([['Lisbon', 1], ['Madrid', 2], ...], 2) %>
|
448
|
-
|
449
|
-
output:
|
450
|
-
|
451
|
-
<option value="1">Lisbon</option>
|
452
|
-
<option value="2" selected="selected">Madrid</option>
|
453
|
-
...
|
454
|
-
</pre>
|
455
|
-
</div>
|
456
|
-
<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>
|
457
|
-
<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>
|
458
|
-
<h4 id="select-boxes-for-dealing-with-models">3.2 Select Boxes for Dealing with Models</h4>
|
459
|
-
<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>
|
460
|
-
<div class="code_container">
|
461
|
-
<pre class="brush: ruby; gutter: false; toolbar: false">
|
462
|
-
# controller:
|
463
|
-
@person = Person.new(:city_id => 2)
|
464
|
-
</pre>
|
465
|
-
</div>
|
466
|
-
<div class="code_container">
|
467
|
-
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
|
468
|
-
# view:
|
469
|
-
<%= select(:person, :city_id, [['Lisbon', 1], ['Madrid', 2], ...]) %>
|
470
|
-
</pre>
|
471
|
-
</div>
|
472
|
-
<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>
|
473
|
-
<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>
|
474
|
-
<div class="code_container">
|
475
|
-
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
|
476
|
-
# select on a form builder
|
477
|
-
<%= f.select(:city_id, ...) %>
|
478
|
-
</pre>
|
479
|
-
</div>
|
480
|
-
<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>
|
481
|
-
<h4 id="option-tags-from-a-collection-of-arbitrary-objects">3.3 Option Tags from a Collection of Arbitrary Objects</h4>
|
482
|
-
<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>
|
483
|
-
<div class="code_container">
|
484
|
-
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
|
485
|
-
<% cities_array = City.all.map { |city| [city.name, city.id] } %>
|
486
|
-
<%= options_for_select(cities_array) %>
|
487
|
-
</pre>
|
488
|
-
</div>
|
489
|
-
<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>
|
490
|
-
<div class="code_container">
|
491
|
-
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
|
492
|
-
<%= options_from_collection_for_select(City.all, :id, :name) %>
|
493
|
-
</pre>
|
494
|
-
</div>
|
495
|
-
<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>
|
496
|
-
<div class="code_container">
|
497
|
-
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
|
498
|
-
<%= collection_select(:person, :city_id, City.all, :id, :name) %>
|
499
|
-
</pre>
|
500
|
-
</div>
|
501
|
-
<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>
|
502
|
-
<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>
|
503
|
-
<h4 id="time-zone-and-country-select">3.4 Time Zone and Country Select</h4>
|
504
|
-
<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>
|
505
|
-
<div class="code_container">
|
506
|
-
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
|
507
|
-
<%= time_zone_select(:person, :time_zone) %>
|
508
|
-
</pre>
|
509
|
-
</div>
|
510
|
-
<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>
|
511
|
-
<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="https://github.com/chrislerum/country_select">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>
|
512
|
-
<h3 id="using-date-and-time-form-helpers">4 Using Date and Time Form Helpers</h3>
|
513
|
-
<p>The date and time helpers differ from all the other form helpers in two important respects:</p>
|
514
|
-
<ol>
|
515
|
-
<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>
|
516
|
-
<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>
|
517
|
-
</ol>
|
518
|
-
<p>Both of these families of helpers will create a series of select boxes for the different components (year, month, day etc.).</p>
|
519
|
-
<h4 id="barebones-helpers">4.1 Barebones Helpers</h4>
|
520
|
-
<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>
|
521
|
-
<div class="code_container">
|
522
|
-
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
|
523
|
-
<%= select_date Date.today, :prefix => :start_date %>
|
524
|
-
</pre>
|
525
|
-
</div>
|
526
|
-
<p>outputs (with actual option values omitted for brevity)</p>
|
527
|
-
<div class="code_container">
|
528
|
-
<pre class="brush: xml; gutter: false; toolbar: false">
|
529
|
-
<select id="start_date_year" name="start_date[year]"> ... </select>
|
530
|
-
<select id="start_date_month" name="start_date[month]"> ... </select>
|
531
|
-
<select id="start_date_day" name="start_date[day]"> ... </select>
|
532
|
-
</pre>
|
533
|
-
</div>
|
534
|
-
<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>
|
535
|
-
<div class="code_container">
|
536
|
-
<pre class="brush: ruby; gutter: false; toolbar: false">
|
537
|
-
Date.civil(params[:start_date][:year].to_i, params[:start_date][:month].to_i, params[:start_date][:day].to_i)
|
538
|
-
</pre>
|
539
|
-
</div>
|
540
|
-
<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>
|
541
|
-
<h4 id="select-model-object-helpers">4.2 Model Object Helpers</h4>
|
542
|
-
<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.
|
543
|
-
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>
|
544
|
-
<div class="code_container">
|
545
|
-
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
|
546
|
-
<%= date_select :person, :birth_date %>
|
547
|
-
</pre>
|
548
|
-
</div>
|
549
|
-
<p>outputs (with actual option values omitted for brevity)</p>
|
550
|
-
<div class="code_container">
|
551
|
-
<pre class="brush: xml; gutter: false; toolbar: false">
|
552
|
-
<select id="person_birth_date_1i" name="person[birth_date(1i)]"> ... </select>
|
553
|
-
<select id="person_birth_date_2i" name="person[birth_date(2i)]"> ... </select>
|
554
|
-
<select id="person_birth_date_3i" name="person[birth_date(3i)]"> ... </select>
|
555
|
-
</pre>
|
556
|
-
</div>
|
557
|
-
<p>which results in a <tt>params</tt> hash like</p>
|
558
|
-
<div class="code_container">
|
559
|
-
<pre class="brush: ruby; gutter: false; toolbar: false">
|
560
|
-
{:person => {'birth_date(1i)' => '2008', 'birth_date(2i)' => '11', 'birth_date(3i)' => '22'}}
|
561
|
-
</pre>
|
562
|
-
</div>
|
563
|
-
<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>
|
564
|
-
<h4 id="common-options">4.3 Common Options</h4>
|
565
|
-
<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>
|
566
|
-
<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>
|
567
|
-
<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>
|
568
|
-
<h4 id="individual-components">4.4 Individual Components</h4>
|
569
|
-
<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 overridden 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>
|
570
|
-
<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>
|
571
|
-
<div class="code_container">
|
572
|
-
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
|
573
|
-
<%= select_year(2009) %>
|
574
|
-
<%= select_year(Time.now) %>
|
575
|
-
</pre>
|
576
|
-
</div>
|
577
|
-
<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>
|
578
|
-
<h3 id="uploading-files">5 Uploading Files</h3>
|
579
|
-
<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>
|
580
|
-
<p>The following two forms both upload a file.</p>
|
581
|
-
<div class="code_container">
|
582
|
-
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
|
583
|
-
<%= form_tag({:action => :upload}, :multipart => true) do %>
|
584
|
-
<%= file_field_tag 'picture' %>
|
585
|
-
<% end %>
|
586
|
-
|
587
|
-
<%= form_for @person do |f| %>
|
588
|
-
<%= f.file_field :picture %>
|
589
|
-
<% end %>
|
590
|
-
</pre>
|
591
|
-
</div>
|
592
|
-
<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>
|
593
|
-
<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>
|
594
|
-
<h4 id="what-gets-uploaded">5.1 What Gets Uploaded</h4>
|
595
|
-
<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>
|
596
|
-
<div class="code_container">
|
597
|
-
<pre class="brush: ruby; gutter: false; toolbar: false">
|
598
|
-
def upload
|
599
|
-
uploaded_io = params[:person][:picture]
|
600
|
-
File.open(Rails.root.join('public', 'uploads', uploaded_io.original_filename), 'w') do |file|
|
601
|
-
file.write(uploaded_io.read)
|
602
|
-
end
|
603
|
-
end
|
604
|
-
</pre>
|
605
|
-
</div>
|
606
|
-
<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 libraries designed to assist with these. Two of the better known ones are <a href="https://github.com/jnicklas/carrierwave">CarrierWave</a> and <a href="http://www.thoughtbot.com/projects/paperclip">Paperclip</a>.</p>
|
607
|
-
<div class="note"><p>If the user has not selected a file the corresponding parameter will be an empty string.</p></div>
|
608
|
-
<h4 id="dealing-with-ajax">5.2 Dealing with Ajax</h4>
|
609
|
-
<p>Unlike other forms making an asynchronous file upload form is not as simple as providing <tt>form_for</tt> with <tt>:remote => true</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>
|
610
|
-
<h3 id="customizing-form-builders">6 Customizing Form Builders</h3>
|
611
|
-
<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>
|
612
|
-
<div class="code_container">
|
613
|
-
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
|
614
|
-
<%= form_for @person do |f| %>
|
615
|
-
<%= text_field_with_label f, :first_name %>
|
616
|
-
<% end %>
|
617
|
-
</pre>
|
618
|
-
</div>
|
619
|
-
<p>can be replaced with</p>
|
620
|
-
<div class="code_container">
|
621
|
-
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
|
622
|
-
<%= form_for @person, :builder => LabellingFormBuilder do |f| %>
|
623
|
-
<%= f.text_field :first_name %>
|
624
|
-
<% end %>
|
625
|
-
</pre>
|
626
|
-
</div>
|
627
|
-
<p>by defining a LabellingFormBuilder class similar to the following:</p>
|
628
|
-
<div class="code_container">
|
629
|
-
<pre class="brush: ruby; gutter: false; toolbar: false">
|
630
|
-
class LabellingFormBuilder < ActionView::Helpers::FormBuilder
|
631
|
-
def text_field(attribute, options={})
|
632
|
-
label(attribute) + super
|
633
|
-
end
|
634
|
-
end
|
635
|
-
</pre>
|
636
|
-
</div>
|
637
|
-
<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>
|
638
|
-
<p>The form builder used also determines what happens when you do</p>
|
639
|
-
<div class="code_container">
|
640
|
-
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
|
641
|
-
<%= render :partial => f %>
|
642
|
-
</pre>
|
643
|
-
</div>
|
644
|
-
<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>
|
645
|
-
<h3 id="understanding-parameter-naming-conventions">7 Understanding Parameter Naming Conventions</h3>
|
646
|
-
<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>
|
647
|
-
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>
|
648
|
-
<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>
|
649
|
-
<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>
|
650
|
-
<div class="code_container">
|
651
|
-
<pre class="brush: ruby; gutter: false; toolbar: false">
|
652
|
-
ActionController::UrlEncodedPairParser.parse_query_parameters "name=fred&phone=0123456789"
|
653
|
-
# => {"name"=>"fred", "phone"=>"0123456789"}
|
654
|
-
</pre>
|
655
|
-
</div>
|
656
|
-
<h4 id="basic-structures">7.1 Basic Structures</h4>
|
657
|
-
<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>
|
658
|
-
<div class="code_container">
|
659
|
-
<pre class="brush: xml; gutter: false; toolbar: false">
|
660
|
-
<input id="person_name" name="person[name]" type="text" value="Henry"/>
|
661
|
-
</pre>
|
662
|
-
</div>
|
663
|
-
<p>the <tt>params</tt> hash will contain</p>
|
664
|
-
<div class="code_container">
|
665
|
-
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
|
666
|
-
{'person' => {'name' => 'Henry'}}
|
667
|
-
</pre>
|
668
|
-
</div>
|
669
|
-
<p>and <tt>params[:person][:name]</tt> will retrieve the submitted value in the controller.</p>
|
670
|
-
<p>Hashes can be nested as many levels as required, for example</p>
|
671
|
-
<div class="code_container">
|
672
|
-
<pre class="brush: xml; gutter: false; toolbar: false">
|
673
|
-
<input id="person_address_city" name="person[address][city]" type="text" value="New York"/>
|
674
|
-
</pre>
|
675
|
-
</div>
|
676
|
-
<p>will result in the <tt>params</tt> hash being</p>
|
677
|
-
<div class="code_container">
|
678
|
-
<pre class="brush: ruby; gutter: false; toolbar: false">
|
679
|
-
{'person' => {'address' => {'city' => 'New York'}}}
|
680
|
-
</pre>
|
681
|
-
</div>
|
682
|
-
<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>
|
683
|
-
<div class="code_container">
|
684
|
-
<pre class="brush: xml; gutter: false; toolbar: false">
|
685
|
-
<input name="person[phone_number][]" type="text"/>
|
686
|
-
<input name="person[phone_number][]" type="text"/>
|
687
|
-
<input name="person[phone_number][]" type="text"/>
|
688
|
-
</pre>
|
689
|
-
</div>
|
690
|
-
<p>This would result in <tt>params[:person][:phone_number]</tt> being an array.</p>
|
691
|
-
<h4 id="combining-them">7.2 Combining Them</h4>
|
692
|
-
<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>
|
693
|
-
<div class="code_container">
|
694
|
-
<pre class="brush: xml; gutter: false; toolbar: false">
|
695
|
-
<input name="addresses[][line1]" type="text"/>
|
696
|
-
<input name="addresses[][line2]" type="text"/>
|
697
|
-
<input name="addresses[][city]" type="text"/>
|
698
|
-
</pre>
|
699
|
-
</div>
|
700
|
-
<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>
|
701
|
-
<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>
|
702
|
-
<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>
|
703
|
-
<h4 id="using-form-helpers">7.3 Using Form Helpers</h4>
|
704
|
-
<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>
|
705
|
-
<p>You might want to render a form with a set of edit fields for each of a person’s addresses. For example:</p>
|
706
|
-
<div class="code_container">
|
707
|
-
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
|
708
|
-
<%= form_for @person do |person_form| %>
|
709
|
-
<%= person_form.text_field :name %>
|
710
|
-
<% @person.addresses.each do |address| %>
|
711
|
-
<%= person_form.fields_for address, :index => address do |address_form|%>
|
712
|
-
<%= address_form.text_field :city %>
|
713
|
-
<% end %>
|
714
|
-
<% end %>
|
715
|
-
<% end %>
|
716
|
-
</pre>
|
717
|
-
</div>
|
718
|
-
<p>Assuming the person had two addresses, with ids 23 and 45 this would create output similar to this:</p>
|
719
|
-
<div class="code_container">
|
720
|
-
<pre class="brush: xml; gutter: false; toolbar: false">
|
721
|
-
<form accept-charset="UTF-8" action="/people/1" class="edit_person" id="edit_person_1" method="post">
|
722
|
-
<input id="person_name" name="person[name]" size="30" type="text" />
|
723
|
-
<input id="person_address_23_city" name="person[address][23][city]" size="30" type="text" />
|
724
|
-
<input id="person_address_45_city" name="person[address][45][city]" size="30" type="text" />
|
725
|
-
</form>
|
726
|
-
</pre>
|
727
|
-
</div>
|
728
|
-
<p>This will result in a <tt>params</tt> hash that looks like</p>
|
729
|
-
<div class="code_container">
|
730
|
-
<pre class="brush: ruby; gutter: false; toolbar: false">
|
731
|
-
{'person' => {'name' => 'Bob', 'address' => {'23' => {'city' => 'Paris'}, '45' => {'city' => 'London'}}}}
|
732
|
-
</pre>
|
733
|
-
</div>
|
734
|
-
<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>
|
735
|
-
<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>
|
736
|
-
<div class="code_container">
|
737
|
-
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
|
738
|
-
<%= fields_for 'person[address][primary]', address, :index => address do |address_form| %>
|
739
|
-
<%= address_form.text_field :city %>
|
740
|
-
<% end %>
|
741
|
-
</pre>
|
742
|
-
</div>
|
743
|
-
<p>will create inputs like</p>
|
744
|
-
<div class="code_container">
|
745
|
-
<pre class="brush: xml; gutter: false; toolbar: false">
|
746
|
-
<input id="person_address_primary_1_city" name="person[address][primary][1][city]" size="30" type="text" value="bologna" />
|
747
|
-
</pre>
|
748
|
-
</div>
|
749
|
-
<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>
|
750
|
-
<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>
|
751
|
-
<div class="code_container">
|
752
|
-
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
|
753
|
-
<%= fields_for 'person[address][primary][]', address do |address_form| %>
|
754
|
-
<%= address_form.text_field :city %>
|
755
|
-
<% end %>
|
756
|
-
</pre>
|
757
|
-
</div>
|
758
|
-
<p>produces exactly the same output as the previous example.</p>
|
759
|
-
<h3 id="forms-to-external-resources">8 Forms to external resources</h3>
|
760
|
-
<p>If you need to post some data to an external resource it is still great to build your from using rails form helpers. But sometimes you need to set an <tt>authenticity_token</tt> for this resource. You can do it by passing an <tt>:authenticity_token => 'your_external_token'</tt> parameter to the <tt>form_tag</tt> options:</p>
|
761
|
-
<div class="code_container">
|
762
|
-
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
|
763
|
-
<%= form_tag 'http://farfar.away/form', :authenticity_token => 'external_token') do %>
|
764
|
-
Form contents
|
765
|
-
<% end %>
|
766
|
-
</pre>
|
767
|
-
</div>
|
768
|
-
<p>Sometimes when you submit data to an external resource, like payment gateway, fields you can use in your form are limited by an external <span class="caps">API</span>. So you may want not to generate an <tt>authenticity_token</tt> hidden field at all. For doing this just pass <tt>false</tt> to the <tt>:authenticity_token</tt> option:</p>
|
769
|
-
<div class="code_container">
|
770
|
-
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
|
771
|
-
<%= form_tag 'http://farfar.away/form', :authenticity_token => false) do %>
|
772
|
-
Form contents
|
773
|
-
<% end %>
|
774
|
-
</pre>
|
775
|
-
</div>
|
776
|
-
<p>The same technique is available for the <tt>form_for</tt> too:</p>
|
777
|
-
<div class="code_container">
|
778
|
-
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
|
779
|
-
<%= form_for @invoice, :url => external_url, :authenticity_token => 'external_token' do |f|
|
780
|
-
Form contents
|
781
|
-
<% end %>
|
782
|
-
</pre>
|
783
|
-
</div>
|
784
|
-
<p>Or if you don’t want to render an <tt>authenticity_token</tt> field:</p>
|
785
|
-
<div class="code_container">
|
786
|
-
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
|
787
|
-
<%= form_for @invoice, :url => external_url, :authenticity_token => false do |f|
|
788
|
-
Form contents
|
789
|
-
<% end %>
|
790
|
-
</pre>
|
791
|
-
</div>
|
792
|
-
<h3 id="building-complex-forms">9 Building Complex Forms</h3>
|
793
|
-
<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>
|
794
|
-
<ul>
|
795
|
-
<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>
|
796
|
-
<li>Ryan Bates’ series of Railscasts on <a href="http://railscasts.com/episodes/75">complex forms</a></li>
|
797
|
-
<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>
|
798
|
-
<li>Eloy Duran’s <a href="https://github.com/alloy/complex-form-examples/">complex-forms-examples</a> application</li>
|
799
|
-
<li>Lance Ivy’s <a href="https://github.com/cainlevy/nested_assignment/tree/master">nested_assignment</a> plugin and <a href="https://github.com/cainlevy/complex-form-examples/tree/cainlevy">sample application</a></li>
|
800
|
-
<li>James Golick’s <a href="https://github.com/jamesgolick/attribute_fu">attribute_fu</a> plugin</li>
|
801
|
-
</ul>
|
802
|
-
|
803
|
-
<h3>Feedback</h3>
|
804
|
-
<p>
|
805
|
-
You're encouraged to help improve the quality of this guide.
|
806
|
-
</p>
|
807
|
-
<p>
|
808
|
-
If you see any typos or factual errors you are confident to
|
809
|
-
patch, please clone <a href="https://github.com/lifo/docrails">docrails</a>
|
810
|
-
and push the change yourself. That branch of Rails has public write access.
|
811
|
-
Commits are still reviewed, but that happens after you've submitted your
|
812
|
-
contribution. <a href="https://github.com/lifo/docrails">docrails</a> is
|
813
|
-
cross-merged with master periodically.
|
814
|
-
</p>
|
815
|
-
<p>
|
816
|
-
You may also find incomplete content, or stuff that is not up to date.
|
817
|
-
Please do add any missing documentation for master. Check the
|
818
|
-
<a href="ruby_on_rails_guides_guidelines.html">Ruby on Rails Guides Guidelines</a>
|
819
|
-
for style and conventions.
|
820
|
-
</p>
|
821
|
-
<p>
|
822
|
-
If for whatever reason you spot something to fix but cannot patch it yourself, please
|
823
|
-
<a href="https://github.com/rails/rails/issues">open an issue</a>.
|
824
|
-
</p>
|
825
|
-
<p>And last but not least, any kind of discussion regarding Ruby on Rails
|
826
|
-
documentation is very welcome in the <a href="http://groups.google.com/group/rubyonrails-docs">rubyonrails-docs mailing list</a>.
|
827
|
-
</p>
|
828
|
-
</div>
|
829
|
-
</div>
|
830
|
-
</div>
|
831
|
-
|
832
|
-
<hr class="hide" />
|
833
|
-
<div id="footer">
|
834
|
-
<div class="wrapper">
|
835
|
-
<p>This work is licensed under a <a href="http://creativecommons.org/licenses/by-sa/3.0/">Creative Commons Attribution-Share Alike 3.0</a> License</p>
|
836
|
-
<p>"Rails", "Ruby on Rails", and the Rails logo are trademarks of David Heinemeier Hansson. All rights reserved.</p>
|
837
|
-
</div>
|
838
|
-
</div>
|
839
|
-
|
840
|
-
<script type="text/javascript" src="javascripts/guides.js"></script>
|
841
|
-
<script type="text/javascript" src="javascripts/syntaxhighlighter/shCore.js"></script>
|
842
|
-
<script type="text/javascript" src="javascripts/syntaxhighlighter/shBrushRuby.js"></script>
|
843
|
-
<script type="text/javascript" src="javascripts/syntaxhighlighter/shBrushXml.js"></script>
|
844
|
-
<script type="text/javascript" src="javascripts/syntaxhighlighter/shBrushSql.js"></script>
|
845
|
-
<script type="text/javascript" src="javascripts/syntaxhighlighter/shBrushPlain.js"></script>
|
846
|
-
<script type="text/javascript">
|
847
|
-
SyntaxHighlighter.all()
|
848
|
-
</script>
|
849
|
-
</body>
|
850
|
-
</html>
|