rails 4.2.7.1 → 6.1.2.1
Sign up to get free protection for your applications and to get access to all the features.
- checksums.yaml +5 -5
- data/README.md +54 -36
- metadata +87 -249
- data/guides/CHANGELOG.md +0 -78
- data/guides/Rakefile +0 -79
- data/guides/assets/images/akshaysurve.jpg +0 -0
- data/guides/assets/images/belongs_to.png +0 -0
- data/guides/assets/images/book_icon.gif +0 -0
- data/guides/assets/images/bullet.gif +0 -0
- data/guides/assets/images/chapters_icon.gif +0 -0
- data/guides/assets/images/check_bullet.gif +0 -0
- data/guides/assets/images/credits_pic_blank.gif +0 -0
- data/guides/assets/images/csrf.png +0 -0
- data/guides/assets/images/edge_badge.png +0 -0
- data/guides/assets/images/favicon.ico +0 -0
- data/guides/assets/images/feature_tile.gif +0 -0
- data/guides/assets/images/footer_tile.gif +0 -0
- data/guides/assets/images/fxn.png +0 -0
- data/guides/assets/images/getting_started/article_with_comments.png +0 -0
- data/guides/assets/images/getting_started/challenge.png +0 -0
- data/guides/assets/images/getting_started/confirm_dialog.png +0 -0
- data/guides/assets/images/getting_started/forbidden_attributes_for_new_article.png +0 -0
- data/guides/assets/images/getting_started/form_with_errors.png +0 -0
- data/guides/assets/images/getting_started/index_action_with_edit_link.png +0 -0
- data/guides/assets/images/getting_started/new_article.png +0 -0
- data/guides/assets/images/getting_started/rails_welcome.png +0 -0
- data/guides/assets/images/getting_started/routing_error_no_controller.png +0 -0
- data/guides/assets/images/getting_started/routing_error_no_route_matches.png +0 -0
- data/guides/assets/images/getting_started/show_action_for_articles.png +0 -0
- data/guides/assets/images/getting_started/template_is_missing_articles_new.png +0 -0
- data/guides/assets/images/getting_started/unknown_action_create_for_articles.png +0 -0
- data/guides/assets/images/getting_started/unknown_action_new_for_articles.png +0 -0
- data/guides/assets/images/grey_bullet.gif +0 -0
- data/guides/assets/images/habtm.png +0 -0
- data/guides/assets/images/has_many.png +0 -0
- data/guides/assets/images/has_many_through.png +0 -0
- data/guides/assets/images/has_one.png +0 -0
- data/guides/assets/images/has_one_through.png +0 -0
- data/guides/assets/images/header_backdrop.png +0 -0
- data/guides/assets/images/header_tile.gif +0 -0
- data/guides/assets/images/i18n/demo_html_safe.png +0 -0
- data/guides/assets/images/i18n/demo_localized_pirate.png +0 -0
- data/guides/assets/images/i18n/demo_translated_en.png +0 -0
- data/guides/assets/images/i18n/demo_translated_pirate.png +0 -0
- data/guides/assets/images/i18n/demo_translation_missing.png +0 -0
- data/guides/assets/images/i18n/demo_untranslated.png +0 -0
- data/guides/assets/images/icons/README +0 -5
- data/guides/assets/images/icons/callouts/1.png +0 -0
- data/guides/assets/images/icons/callouts/10.png +0 -0
- data/guides/assets/images/icons/callouts/11.png +0 -0
- data/guides/assets/images/icons/callouts/12.png +0 -0
- data/guides/assets/images/icons/callouts/13.png +0 -0
- data/guides/assets/images/icons/callouts/14.png +0 -0
- data/guides/assets/images/icons/callouts/15.png +0 -0
- data/guides/assets/images/icons/callouts/2.png +0 -0
- data/guides/assets/images/icons/callouts/3.png +0 -0
- data/guides/assets/images/icons/callouts/4.png +0 -0
- data/guides/assets/images/icons/callouts/5.png +0 -0
- data/guides/assets/images/icons/callouts/6.png +0 -0
- data/guides/assets/images/icons/callouts/7.png +0 -0
- data/guides/assets/images/icons/callouts/8.png +0 -0
- data/guides/assets/images/icons/callouts/9.png +0 -0
- data/guides/assets/images/icons/caution.png +0 -0
- data/guides/assets/images/icons/example.png +0 -0
- data/guides/assets/images/icons/home.png +0 -0
- data/guides/assets/images/icons/important.png +0 -0
- data/guides/assets/images/icons/next.png +0 -0
- data/guides/assets/images/icons/note.png +0 -0
- data/guides/assets/images/icons/prev.png +0 -0
- data/guides/assets/images/icons/tip.png +0 -0
- data/guides/assets/images/icons/up.png +0 -0
- data/guides/assets/images/icons/warning.png +0 -0
- data/guides/assets/images/nav_arrow.gif +0 -0
- data/guides/assets/images/oscardelben.jpg +0 -0
- data/guides/assets/images/polymorphic.png +0 -0
- data/guides/assets/images/radar.png +0 -0
- data/guides/assets/images/rails4_features.png +0 -0
- data/guides/assets/images/rails_guides_kindle_cover.jpg +0 -0
- data/guides/assets/images/rails_guides_logo.gif +0 -0
- data/guides/assets/images/rails_logo_remix.gif +0 -0
- data/guides/assets/images/session_fixation.png +0 -0
- data/guides/assets/images/tab_grey.gif +0 -0
- data/guides/assets/images/tab_info.gif +0 -0
- data/guides/assets/images/tab_note.gif +0 -0
- data/guides/assets/images/tab_red.gif +0 -0
- data/guides/assets/images/tab_yellow.gif +0 -0
- data/guides/assets/images/tab_yellow.png +0 -0
- data/guides/assets/images/vijaydev.jpg +0 -0
- data/guides/assets/javascripts/guides.js +0 -59
- data/guides/assets/javascripts/jquery.min.js +0 -4
- data/guides/assets/javascripts/responsive-tables.js +0 -43
- data/guides/assets/javascripts/syntaxhighlighter/shBrushAS3.js +0 -59
- data/guides/assets/javascripts/syntaxhighlighter/shBrushAppleScript.js +0 -75
- data/guides/assets/javascripts/syntaxhighlighter/shBrushBash.js +0 -59
- data/guides/assets/javascripts/syntaxhighlighter/shBrushCSharp.js +0 -65
- data/guides/assets/javascripts/syntaxhighlighter/shBrushColdFusion.js +0 -100
- data/guides/assets/javascripts/syntaxhighlighter/shBrushCpp.js +0 -97
- data/guides/assets/javascripts/syntaxhighlighter/shBrushCss.js +0 -91
- data/guides/assets/javascripts/syntaxhighlighter/shBrushDelphi.js +0 -55
- data/guides/assets/javascripts/syntaxhighlighter/shBrushDiff.js +0 -41
- data/guides/assets/javascripts/syntaxhighlighter/shBrushErlang.js +0 -52
- data/guides/assets/javascripts/syntaxhighlighter/shBrushGroovy.js +0 -67
- data/guides/assets/javascripts/syntaxhighlighter/shBrushJScript.js +0 -52
- data/guides/assets/javascripts/syntaxhighlighter/shBrushJava.js +0 -57
- data/guides/assets/javascripts/syntaxhighlighter/shBrushJavaFX.js +0 -58
- data/guides/assets/javascripts/syntaxhighlighter/shBrushPerl.js +0 -72
- data/guides/assets/javascripts/syntaxhighlighter/shBrushPhp.js +0 -88
- data/guides/assets/javascripts/syntaxhighlighter/shBrushPlain.js +0 -33
- data/guides/assets/javascripts/syntaxhighlighter/shBrushPowerShell.js +0 -74
- data/guides/assets/javascripts/syntaxhighlighter/shBrushPython.js +0 -64
- data/guides/assets/javascripts/syntaxhighlighter/shBrushRuby.js +0 -55
- data/guides/assets/javascripts/syntaxhighlighter/shBrushSass.js +0 -94
- data/guides/assets/javascripts/syntaxhighlighter/shBrushScala.js +0 -51
- data/guides/assets/javascripts/syntaxhighlighter/shBrushSql.js +0 -66
- data/guides/assets/javascripts/syntaxhighlighter/shBrushVb.js +0 -56
- data/guides/assets/javascripts/syntaxhighlighter/shBrushXml.js +0 -69
- data/guides/assets/javascripts/syntaxhighlighter/shCore.js +0 -17
- data/guides/assets/stylesheets/fixes.css +0 -16
- data/guides/assets/stylesheets/kindle.css +0 -11
- data/guides/assets/stylesheets/main.css +0 -713
- data/guides/assets/stylesheets/print.css +0 -52
- data/guides/assets/stylesheets/reset.css +0 -43
- data/guides/assets/stylesheets/responsive-tables.css +0 -50
- data/guides/assets/stylesheets/style.css +0 -13
- data/guides/assets/stylesheets/syntaxhighlighter/shCore.css +0 -226
- data/guides/assets/stylesheets/syntaxhighlighter/shCoreDefault.css +0 -328
- data/guides/assets/stylesheets/syntaxhighlighter/shCoreDjango.css +0 -331
- data/guides/assets/stylesheets/syntaxhighlighter/shCoreEclipse.css +0 -339
- data/guides/assets/stylesheets/syntaxhighlighter/shCoreEmacs.css +0 -324
- data/guides/assets/stylesheets/syntaxhighlighter/shCoreFadeToGrey.css +0 -328
- data/guides/assets/stylesheets/syntaxhighlighter/shCoreMDUltra.css +0 -324
- data/guides/assets/stylesheets/syntaxhighlighter/shCoreMidnight.css +0 -324
- data/guides/assets/stylesheets/syntaxhighlighter/shCoreRDark.css +0 -324
- data/guides/assets/stylesheets/syntaxhighlighter/shThemeDefault.css +0 -117
- data/guides/assets/stylesheets/syntaxhighlighter/shThemeDjango.css +0 -120
- data/guides/assets/stylesheets/syntaxhighlighter/shThemeEclipse.css +0 -128
- data/guides/assets/stylesheets/syntaxhighlighter/shThemeEmacs.css +0 -113
- data/guides/assets/stylesheets/syntaxhighlighter/shThemeFadeToGrey.css +0 -117
- data/guides/assets/stylesheets/syntaxhighlighter/shThemeMDUltra.css +0 -113
- data/guides/assets/stylesheets/syntaxhighlighter/shThemeMidnight.css +0 -113
- data/guides/assets/stylesheets/syntaxhighlighter/shThemeRDark.css +0 -113
- data/guides/assets/stylesheets/syntaxhighlighter/shThemeRailsGuides.css +0 -116
- data/guides/bug_report_templates/action_controller_gem.rb +0 -47
- data/guides/bug_report_templates/action_controller_master.rb +0 -54
- data/guides/bug_report_templates/active_record_gem.rb +0 -40
- data/guides/bug_report_templates/active_record_master.rb +0 -49
- data/guides/bug_report_templates/generic_gem.rb +0 -15
- data/guides/bug_report_templates/generic_master.rb +0 -26
- data/guides/rails_guides.rb +0 -63
- data/guides/rails_guides/generator.rb +0 -248
- data/guides/rails_guides/helpers.rb +0 -53
- data/guides/rails_guides/indexer.rb +0 -68
- data/guides/rails_guides/kindle.rb +0 -119
- data/guides/rails_guides/levenshtein.rb +0 -37
- data/guides/rails_guides/markdown.rb +0 -167
- data/guides/rails_guides/markdown/renderer.rb +0 -82
- data/guides/source/2_2_release_notes.md +0 -435
- data/guides/source/2_3_release_notes.md +0 -621
- data/guides/source/3_0_release_notes.md +0 -611
- data/guides/source/3_1_release_notes.md +0 -559
- data/guides/source/3_2_release_notes.md +0 -568
- data/guides/source/4_0_release_notes.md +0 -279
- data/guides/source/4_1_release_notes.md +0 -730
- data/guides/source/4_2_release_notes.md +0 -877
- data/guides/source/_license.html.erb +0 -2
- data/guides/source/_welcome.html.erb +0 -23
- data/guides/source/action_controller_overview.md +0 -1192
- data/guides/source/action_mailer_basics.md +0 -757
- data/guides/source/action_view_overview.md +0 -1561
- data/guides/source/active_job_basics.md +0 -339
- data/guides/source/active_model_basics.md +0 -554
- data/guides/source/active_record_basics.md +0 -374
- data/guides/source/active_record_callbacks.md +0 -413
- data/guides/source/active_record_migrations.md +0 -1018
- data/guides/source/active_record_postgresql.md +0 -433
- data/guides/source/active_record_querying.md +0 -1781
- data/guides/source/active_record_validations.md +0 -1179
- data/guides/source/active_support_core_extensions.md +0 -3857
- data/guides/source/active_support_instrumentation.md +0 -488
- data/guides/source/api_documentation_guidelines.md +0 -361
- data/guides/source/asset_pipeline.md +0 -1304
- data/guides/source/association_basics.md +0 -2245
- data/guides/source/autoloading_and_reloading_constants.md +0 -1311
- data/guides/source/caching_with_rails.md +0 -379
- data/guides/source/command_line.md +0 -625
- data/guides/source/configuring.md +0 -1072
- data/guides/source/contributing_to_ruby_on_rails.md +0 -628
- data/guides/source/credits.html.erb +0 -80
- data/guides/source/debugging_rails_applications.md +0 -861
- data/guides/source/development_dependencies_install.md +0 -289
- data/guides/source/documents.yaml +0 -205
- data/guides/source/engines.md +0 -1412
- data/guides/source/form_helpers.md +0 -1024
- data/guides/source/generators.md +0 -676
- data/guides/source/getting_started.md +0 -2086
- data/guides/source/i18n.md +0 -1087
- data/guides/source/index.html.erb +0 -28
- data/guides/source/initialization.md +0 -704
- data/guides/source/kindle/copyright.html.erb +0 -1
- data/guides/source/kindle/layout.html.erb +0 -27
- data/guides/source/kindle/rails_guides.opf.erb +0 -52
- data/guides/source/kindle/toc.html.erb +0 -24
- data/guides/source/kindle/toc.ncx.erb +0 -64
- data/guides/source/kindle/welcome.html.erb +0 -5
- data/guides/source/layout.html.erb +0 -140
- data/guides/source/layouts_and_rendering.md +0 -1226
- data/guides/source/maintenance_policy.md +0 -78
- data/guides/source/nested_model_forms.md +0 -228
- data/guides/source/plugins.md +0 -444
- data/guides/source/rails_application_templates.md +0 -266
- data/guides/source/rails_on_rack.md +0 -336
- data/guides/source/routing.md +0 -1155
- data/guides/source/ruby_on_rails_guides_guidelines.md +0 -127
- data/guides/source/security.md +0 -1024
- data/guides/source/testing.md +0 -1132
- data/guides/source/upgrading_ruby_on_rails.md +0 -1186
- data/guides/source/working_with_javascript_in_rails.md +0 -407
- data/guides/w3c_validator.rb +0 -97
@@ -1,1024 +0,0 @@
|
|
1
|
-
Form Helpers
|
2
|
-
============
|
3
|
-
|
4
|
-
Forms in web applications are an essential interface for user input. However, form markup can quickly become tedious to write and maintain because of the need to handle form control naming and its numerous attributes. Rails does away with this complexity by providing view helpers for generating form markup. However, since these helpers have different use cases, developers need to know the differences between the helper methods before putting them to use.
|
5
|
-
|
6
|
-
After reading this guide, you will know:
|
7
|
-
|
8
|
-
* How to create search forms and similar kind of generic forms not representing any specific model in your application.
|
9
|
-
* How to make model-centric forms for creating and editing specific database records.
|
10
|
-
* How to generate select boxes from multiple types of data.
|
11
|
-
* What date and time helpers Rails provides.
|
12
|
-
* What makes a file upload form different.
|
13
|
-
* How to post forms to external resources and specify setting an `authenticity_token`.
|
14
|
-
* How to build complex forms.
|
15
|
-
|
16
|
-
--------------------------------------------------------------------------------
|
17
|
-
|
18
|
-
NOTE: This guide is not intended to be a complete documentation of available form helpers and their arguments. Please visit [the Rails API documentation](http://api.rubyonrails.org/) for a complete reference.
|
19
|
-
|
20
|
-
Dealing with Basic Forms
|
21
|
-
------------------------
|
22
|
-
|
23
|
-
The most basic form helper is `form_tag`.
|
24
|
-
|
25
|
-
```erb
|
26
|
-
<%= form_tag do %>
|
27
|
-
Form contents
|
28
|
-
<% end %>
|
29
|
-
```
|
30
|
-
|
31
|
-
When called without arguments like this, it creates a `<form>` tag which, when submitted, will POST to the current page. For instance, assuming the current page is `/home/index`, the generated HTML will look like this (some line breaks added for readability):
|
32
|
-
|
33
|
-
```html
|
34
|
-
<form accept-charset="UTF-8" action="/" method="post">
|
35
|
-
<input name="utf8" type="hidden" value="✓" />
|
36
|
-
<input name="authenticity_token" type="hidden" value="J7CBxfHalt49OSHp27hblqK20c9PgwJ108nDHX/8Cts=" />
|
37
|
-
Form contents
|
38
|
-
</form>
|
39
|
-
```
|
40
|
-
|
41
|
-
You'll notice that the HTML contains `input` element with type `hidden`. This `input` is important, because the form cannot be successfully submitted without it. The hidden input element has name attribute of `utf8` enforces browsers to properly respect your form's character encoding and is generated for all forms whether their actions are "GET" or "POST". The second input element with name `authenticity_token` is a security feature of Rails called **cross-site request forgery protection**, and form helpers generate it for every non-GET form (provided that this security feature is enabled). You can read more about this in the [Security Guide](security.html#cross-site-request-forgery-csrf).
|
42
|
-
|
43
|
-
### A Generic Search Form
|
44
|
-
|
45
|
-
One of the most basic forms you see on the web is a search form. This form contains:
|
46
|
-
|
47
|
-
* a form element with "GET" method,
|
48
|
-
* a label for the input,
|
49
|
-
* a text input element, and
|
50
|
-
* a submit element.
|
51
|
-
|
52
|
-
To create this form you will use `form_tag`, `label_tag`, `text_field_tag`, and `submit_tag`, respectively. Like this:
|
53
|
-
|
54
|
-
```erb
|
55
|
-
<%= form_tag("/search", method: "get") do %>
|
56
|
-
<%= label_tag(:q, "Search for:") %>
|
57
|
-
<%= text_field_tag(:q) %>
|
58
|
-
<%= submit_tag("Search") %>
|
59
|
-
<% end %>
|
60
|
-
```
|
61
|
-
|
62
|
-
This will generate the following HTML:
|
63
|
-
|
64
|
-
```html
|
65
|
-
<form accept-charset="UTF-8" action="/search" method="get">
|
66
|
-
<input name="utf8" type="hidden" value="✓" />
|
67
|
-
<label for="q">Search for:</label>
|
68
|
-
<input id="q" name="q" type="text" />
|
69
|
-
<input name="commit" type="submit" value="Search" />
|
70
|
-
</form>
|
71
|
-
```
|
72
|
-
|
73
|
-
TIP: For every form input, an ID attribute is generated from its name (`"q"` in above example). These IDs can be very useful for CSS styling or manipulation of form controls with JavaScript.
|
74
|
-
|
75
|
-
Besides `text_field_tag` and `submit_tag`, there is a similar helper for _every_ form control in HTML.
|
76
|
-
|
77
|
-
IMPORTANT: Always use "GET" 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 HTTP verb for an action.
|
78
|
-
|
79
|
-
### Multiple Hashes in Form Helper Calls
|
80
|
-
|
81
|
-
The `form_tag` helper accepts 2 arguments: the path for the action and an options hash. This hash specifies the method of form submission and HTML options such as the form element's class.
|
82
|
-
|
83
|
-
As with the `link_to` helper, the path argument doesn't have to be a string; it can be a hash of URL parameters recognizable by Rails' routing mechanism, which will turn the hash into a valid URL. However, since both arguments to `form_tag` are hashes, you can easily run into a problem if you would like to specify both. For instance, let's say you write this:
|
84
|
-
|
85
|
-
```ruby
|
86
|
-
form_tag(controller: "people", action: "search", method: "get", class: "nifty_form")
|
87
|
-
# => '<form accept-charset="UTF-8" action="/people/search?method=get&class=nifty_form" method="post">'
|
88
|
-
```
|
89
|
-
|
90
|
-
Here, `method` and `class` are appended to the query string of the generated URL because 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 HTML you expect:
|
91
|
-
|
92
|
-
```ruby
|
93
|
-
form_tag({controller: "people", action: "search"}, method: "get", class: "nifty_form")
|
94
|
-
# => '<form accept-charset="UTF-8" action="/people/search" method="get" class="nifty_form">'
|
95
|
-
```
|
96
|
-
|
97
|
-
### Helpers for Generating Form Elements
|
98
|
-
|
99
|
-
Rails provides a series of helpers for generating form elements such as
|
100
|
-
checkboxes, text fields, and radio buttons. These basic helpers, with names
|
101
|
-
ending in `_tag` (such as `text_field_tag` and `check_box_tag`), generate just a
|
102
|
-
single `<input>` element. The first parameter to these is always the name of the
|
103
|
-
input. When the form is submitted, the name will be passed along with the form
|
104
|
-
data, and will make its way to the `params` hash in the controller with the
|
105
|
-
value entered by the user for that field. For example, if the form contains `<%=
|
106
|
-
text_field_tag(:query) %>`, then you would be able to get the value of this
|
107
|
-
field in the controller with `params[:query]`.
|
108
|
-
|
109
|
-
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 `params`. You can read more about them in [chapter 7 of this guide](#understanding-parameter-naming-conventions). For details on the precise usage of these helpers, please refer to the [API documentation](http://api.rubyonrails.org/classes/ActionView/Helpers/FormTagHelper.html).
|
110
|
-
|
111
|
-
#### Checkboxes
|
112
|
-
|
113
|
-
Checkboxes are form controls that give the user a set of options they can enable or disable:
|
114
|
-
|
115
|
-
```erb
|
116
|
-
<%= check_box_tag(:pet_dog) %>
|
117
|
-
<%= label_tag(:pet_dog, "I own a dog") %>
|
118
|
-
<%= check_box_tag(:pet_cat) %>
|
119
|
-
<%= label_tag(:pet_cat, "I own a cat") %>
|
120
|
-
```
|
121
|
-
|
122
|
-
This generates the following:
|
123
|
-
|
124
|
-
```html
|
125
|
-
<input id="pet_dog" name="pet_dog" type="checkbox" value="1" />
|
126
|
-
<label for="pet_dog">I own a dog</label>
|
127
|
-
<input id="pet_cat" name="pet_cat" type="checkbox" value="1" />
|
128
|
-
<label for="pet_cat">I own a cat</label>
|
129
|
-
```
|
130
|
-
|
131
|
-
The first parameter to `check_box_tag`, 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 `params`) when the checkbox is checked.
|
132
|
-
|
133
|
-
#### Radio Buttons
|
134
|
-
|
135
|
-
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):
|
136
|
-
|
137
|
-
```erb
|
138
|
-
<%= radio_button_tag(:age, "child") %>
|
139
|
-
<%= label_tag(:age_child, "I am younger than 21") %>
|
140
|
-
<%= radio_button_tag(:age, "adult") %>
|
141
|
-
<%= label_tag(:age_adult, "I'm over 21") %>
|
142
|
-
```
|
143
|
-
|
144
|
-
Output:
|
145
|
-
|
146
|
-
```html
|
147
|
-
<input id="age_child" name="age" type="radio" value="child" />
|
148
|
-
<label for="age_child">I am younger than 21</label>
|
149
|
-
<input id="age_adult" name="age" type="radio" value="adult" />
|
150
|
-
<label for="age_adult">I'm over 21</label>
|
151
|
-
```
|
152
|
-
|
153
|
-
As with `check_box_tag`, the second parameter to `radio_button_tag` 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 of them, and `params[:age]` will contain either `"child"` or `"adult"`.
|
154
|
-
|
155
|
-
NOTE: Always use labels for checkbox and radio buttons. They associate text with a specific option and,
|
156
|
-
by expanding the clickable region,
|
157
|
-
make it easier for users to click the inputs.
|
158
|
-
|
159
|
-
### Other Helpers of Interest
|
160
|
-
|
161
|
-
Other form controls worth mentioning are textareas, password fields,
|
162
|
-
hidden fields, search fields, telephone fields, date fields, time fields,
|
163
|
-
color fields, datetime fields, datetime-local fields, month fields, week fields,
|
164
|
-
URL fields, email fields, number fields and range fields:
|
165
|
-
|
166
|
-
```erb
|
167
|
-
<%= text_area_tag(:message, "Hi, nice site", size: "24x6") %>
|
168
|
-
<%= password_field_tag(:password) %>
|
169
|
-
<%= hidden_field_tag(:parent_id, "5") %>
|
170
|
-
<%= search_field(:user, :name) %>
|
171
|
-
<%= telephone_field(:user, :phone) %>
|
172
|
-
<%= date_field(:user, :born_on) %>
|
173
|
-
<%= datetime_field(:user, :meeting_time) %>
|
174
|
-
<%= datetime_local_field(:user, :graduation_day) %>
|
175
|
-
<%= month_field(:user, :birthday_month) %>
|
176
|
-
<%= week_field(:user, :birthday_week) %>
|
177
|
-
<%= url_field(:user, :homepage) %>
|
178
|
-
<%= email_field(:user, :address) %>
|
179
|
-
<%= color_field(:user, :favorite_color) %>
|
180
|
-
<%= time_field(:task, :started_at) %>
|
181
|
-
<%= number_field(:product, :price, in: 1.0..20.0, step: 0.5) %>
|
182
|
-
<%= range_field(:product, :discount, in: 1..100) %>
|
183
|
-
```
|
184
|
-
|
185
|
-
Output:
|
186
|
-
|
187
|
-
```html
|
188
|
-
<textarea id="message" name="message" cols="24" rows="6">Hi, nice site</textarea>
|
189
|
-
<input id="password" name="password" type="password" />
|
190
|
-
<input id="parent_id" name="parent_id" type="hidden" value="5" />
|
191
|
-
<input id="user_name" name="user[name]" type="search" />
|
192
|
-
<input id="user_phone" name="user[phone]" type="tel" />
|
193
|
-
<input id="user_born_on" name="user[born_on]" type="date" />
|
194
|
-
<input id="user_meeting_time" name="user[meeting_time]" type="datetime" />
|
195
|
-
<input id="user_graduation_day" name="user[graduation_day]" type="datetime-local" />
|
196
|
-
<input id="user_birthday_month" name="user[birthday_month]" type="month" />
|
197
|
-
<input id="user_birthday_week" name="user[birthday_week]" type="week" />
|
198
|
-
<input id="user_homepage" name="user[homepage]" type="url" />
|
199
|
-
<input id="user_address" name="user[address]" type="email" />
|
200
|
-
<input id="user_favorite_color" name="user[favorite_color]" type="color" value="#000000" />
|
201
|
-
<input id="task_started_at" name="task[started_at]" type="time" />
|
202
|
-
<input id="product_price" max="20.0" min="1.0" name="product[price]" step="0.5" type="number" />
|
203
|
-
<input id="product_discount" max="100" min="1" name="product[discount]" type="range" />
|
204
|
-
```
|
205
|
-
|
206
|
-
Hidden inputs are not shown to the user but instead hold data like any textual input. Values inside them can be changed with JavaScript.
|
207
|
-
|
208
|
-
IMPORTANT: The search, telephone, date, time, color, datetime, datetime-local,
|
209
|
-
month, week, URL, email, number and range inputs are HTML5 controls.
|
210
|
-
If you require your app to have a consistent experience in older browsers,
|
211
|
-
you will need an HTML5 polyfill (provided by CSS and/or JavaScript).
|
212
|
-
There is definitely [no shortage of solutions for this](https://github.com/Modernizr/Modernizr/wiki/HTML5-Cross-Browser-Polyfills), although a couple of popular tools at the moment are
|
213
|
-
[Modernizr](http://www.modernizr.com/) and [yepnope](http://yepnopejs.com/),
|
214
|
-
which provide a simple way to add functionality based on the presence of
|
215
|
-
detected HTML5 features.
|
216
|
-
|
217
|
-
TIP: 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 [Security Guide](security.html#logging).
|
218
|
-
|
219
|
-
Dealing with Model Objects
|
220
|
-
--------------------------
|
221
|
-
|
222
|
-
### Model Object Helpers
|
223
|
-
|
224
|
-
A particularly common task for a form is editing or creating a model object. While the `*_tag` 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 `text_field`, `text_area`.
|
225
|
-
|
226
|
-
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 `@person` and that person's name is Henry then a form containing:
|
227
|
-
|
228
|
-
```erb
|
229
|
-
<%= text_field(:person, :name) %>
|
230
|
-
```
|
231
|
-
|
232
|
-
will produce output similar to
|
233
|
-
|
234
|
-
```erb
|
235
|
-
<input id="person_name" name="person[name]" type="text" value="Henry"/>
|
236
|
-
```
|
237
|
-
|
238
|
-
Upon form submission the value entered by the user will be stored in `params[:person][:name]`. The `params[:person]` hash is suitable for passing to `Person.new` or, if `@person` is an instance of Person, `@person.update`. 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 `name` and a `name=` method Rails will be happy.
|
239
|
-
|
240
|
-
WARNING: You must pass the name of an instance variable, i.e. `:person` or `"person"`, not an actual instance of your model object.
|
241
|
-
|
242
|
-
Rails provides helpers for displaying the validation errors associated with a model object. These are covered in detail by the [Active Record Validations](./active_record_validations.html#displaying-validation-errors-in-views) guide.
|
243
|
-
|
244
|
-
### Binding a Form to an Object
|
245
|
-
|
246
|
-
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 `form_for` does.
|
247
|
-
|
248
|
-
Assume we have a controller for dealing with articles `app/controllers/articles_controller.rb`:
|
249
|
-
|
250
|
-
```ruby
|
251
|
-
def new
|
252
|
-
@article = Article.new
|
253
|
-
end
|
254
|
-
```
|
255
|
-
|
256
|
-
The corresponding view `app/views/articles/new.html.erb` using `form_for` looks like this:
|
257
|
-
|
258
|
-
```erb
|
259
|
-
<%= form_for @article, url: {action: "create"}, html: {class: "nifty_form"} do |f| %>
|
260
|
-
<%= f.text_field :title %>
|
261
|
-
<%= f.text_area :body, size: "60x12" %>
|
262
|
-
<%= f.submit "Create" %>
|
263
|
-
<% end %>
|
264
|
-
```
|
265
|
-
|
266
|
-
There are a few things to note here:
|
267
|
-
|
268
|
-
* `@article` is the actual object being edited.
|
269
|
-
* There is a single hash of options. Routing options are passed in the `:url` hash, HTML options are passed in the `:html` hash. Also you can provide a `:namespace` option for your form to ensure uniqueness of id attributes on form elements. The namespace attribute will be prefixed with underscore on the generated HTML id.
|
270
|
-
* The `form_for` method yields a **form builder** object (the `f` variable).
|
271
|
-
* Methods to create form controls are called **on** the form builder object `f`.
|
272
|
-
|
273
|
-
The resulting HTML is:
|
274
|
-
|
275
|
-
```html
|
276
|
-
<form accept-charset="UTF-8" action="/articles/create" method="post" class="nifty_form">
|
277
|
-
<input id="article_title" name="article[title]" type="text" />
|
278
|
-
<textarea id="article_body" name="article[body]" cols="60" rows="12"></textarea>
|
279
|
-
<input name="commit" type="submit" value="Create" />
|
280
|
-
</form>
|
281
|
-
```
|
282
|
-
|
283
|
-
The name passed to `form_for` controls the key used in `params` to access the form's values. Here the name is `article` and so all the inputs have names of the form `article[attribute_name]`. Accordingly, in the `create` action `params[:article]` will be a hash with keys `:title` and `:body`. You can read more about the significance of input names in the parameter_names section.
|
284
|
-
|
285
|
-
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.
|
286
|
-
|
287
|
-
You can create a similar binding without actually creating `<form>` tags with the `fields_for` 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:
|
288
|
-
|
289
|
-
```erb
|
290
|
-
<%= form_for @person, url: {action: "create"} do |person_form| %>
|
291
|
-
<%= person_form.text_field :name %>
|
292
|
-
<%= fields_for @person.contact_detail do |contact_details_form| %>
|
293
|
-
<%= contact_details_form.text_field :phone_number %>
|
294
|
-
<% end %>
|
295
|
-
<% end %>
|
296
|
-
```
|
297
|
-
|
298
|
-
which produces the following output:
|
299
|
-
|
300
|
-
```html
|
301
|
-
<form accept-charset="UTF-8" action="/people/create" class="new_person" id="new_person" method="post">
|
302
|
-
<input id="person_name" name="person[name]" type="text" />
|
303
|
-
<input id="contact_detail_phone_number" name="contact_detail[phone_number]" type="text" />
|
304
|
-
</form>
|
305
|
-
```
|
306
|
-
|
307
|
-
The object yielded by `fields_for` is a form builder like the one yielded by `form_for` (in fact `form_for` calls `fields_for` internally).
|
308
|
-
|
309
|
-
### Relying on Record Identification
|
310
|
-
|
311
|
-
The Article model is directly available to users of the application, so - following the best practices for developing with Rails - you should declare it **a resource**:
|
312
|
-
|
313
|
-
```ruby
|
314
|
-
resources :articles
|
315
|
-
```
|
316
|
-
|
317
|
-
TIP: Declaring a resource has a number of side-affects. See [Rails Routing From the Outside In](routing.html#resource-routing-the-rails-default) for more information on setting up and using resources.
|
318
|
-
|
319
|
-
When dealing with RESTful resources, calls to `form_for` can get significantly easier if you rely on **record identification**. In short, you can just pass the model instance and have Rails figure out model name and the rest:
|
320
|
-
|
321
|
-
```ruby
|
322
|
-
## Creating a new article
|
323
|
-
# long-style:
|
324
|
-
form_for(@article, url: articles_path)
|
325
|
-
# same thing, short-style (record identification gets used):
|
326
|
-
form_for(@article)
|
327
|
-
|
328
|
-
## Editing an existing article
|
329
|
-
# long-style:
|
330
|
-
form_for(@article, url: article_path(@article), html: {method: "patch"})
|
331
|
-
# short-style:
|
332
|
-
form_for(@article)
|
333
|
-
```
|
334
|
-
|
335
|
-
Notice how the short-style `form_for` 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 `record.new_record?`. It also selects the correct path to submit to and the name based on the class of the object.
|
336
|
-
|
337
|
-
Rails will also automatically set the `class` and `id` of the form appropriately: a form creating an article would have `id` and `class` `new_article`. If you were editing the article with id 23, the `class` would be set to `edit_article` and the id to `edit_article_23`. These attributes will be omitted for brevity in the rest of this guide.
|
338
|
-
|
339
|
-
WARNING: When you're using STI (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, `:url`, and `:method` explicitly.
|
340
|
-
|
341
|
-
#### Dealing with Namespaces
|
342
|
-
|
343
|
-
If you have created namespaced routes, `form_for` has a nifty shorthand for that too. If your application has an admin namespace then
|
344
|
-
|
345
|
-
```ruby
|
346
|
-
form_for [:admin, @article]
|
347
|
-
```
|
348
|
-
|
349
|
-
will create a form that submits to the `ArticlesController` inside the admin namespace (submitting to `admin_article_path(@article)` in the case of an update). If you have several levels of namespacing then the syntax is similar:
|
350
|
-
|
351
|
-
```ruby
|
352
|
-
form_for [:admin, :management, @article]
|
353
|
-
```
|
354
|
-
|
355
|
-
For more information on Rails' routing system and the associated conventions, please see the [routing guide](routing.html).
|
356
|
-
|
357
|
-
### How do forms with PATCH, PUT, or DELETE methods work?
|
358
|
-
|
359
|
-
The Rails framework encourages RESTful design of your applications, which means you'll be making a lot of "PATCH" and "DELETE" requests (besides "GET" and "POST"). However, most browsers _don't support_ methods other than "GET" and "POST" when it comes to submitting forms.
|
360
|
-
|
361
|
-
Rails works around this issue by emulating other methods over POST with a hidden input named `"_method"`, which is set to reflect the desired method:
|
362
|
-
|
363
|
-
```ruby
|
364
|
-
form_tag(search_path, method: "patch")
|
365
|
-
```
|
366
|
-
|
367
|
-
output:
|
368
|
-
|
369
|
-
```html
|
370
|
-
<form accept-charset="UTF-8" action="/search" method="post">
|
371
|
-
<input name="_method" type="hidden" value="patch" />
|
372
|
-
<input name="utf8" type="hidden" value="✓" />
|
373
|
-
<input name="authenticity_token" type="hidden" value="f755bb0ed134b76c432144748a6d4b7a7ddf2b71" />
|
374
|
-
...
|
375
|
-
</form>
|
376
|
-
```
|
377
|
-
|
378
|
-
When parsing POSTed data, Rails will take into account the special `_method` parameter and acts as if the HTTP method was the one specified inside it ("PATCH" in this example).
|
379
|
-
|
380
|
-
Making Select Boxes with Ease
|
381
|
-
-----------------------------
|
382
|
-
|
383
|
-
Select boxes in HTML require a significant amount of markup (one `OPTION` element for each option to choose from), therefore it makes the most sense for them to be dynamically generated.
|
384
|
-
|
385
|
-
Here is what the markup might look like:
|
386
|
-
|
387
|
-
```html
|
388
|
-
<select name="city_id" id="city_id">
|
389
|
-
<option value="1">Lisbon</option>
|
390
|
-
<option value="2">Madrid</option>
|
391
|
-
...
|
392
|
-
<option value="12">Berlin</option>
|
393
|
-
</select>
|
394
|
-
```
|
395
|
-
|
396
|
-
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.
|
397
|
-
|
398
|
-
### The Select and Option Tags
|
399
|
-
|
400
|
-
The most generic helper is `select_tag`, which - as the name implies - simply generates the `SELECT` tag that encapsulates an options string:
|
401
|
-
|
402
|
-
```erb
|
403
|
-
<%= select_tag(:city_id, '<option value="1">Lisbon</option>...') %>
|
404
|
-
```
|
405
|
-
|
406
|
-
This is a start, but it doesn't dynamically create the option tags. You can generate option tags with the `options_for_select` helper:
|
407
|
-
|
408
|
-
```html+erb
|
409
|
-
<%= options_for_select([['Lisbon', 1], ['Madrid', 2], ...]) %>
|
410
|
-
|
411
|
-
output:
|
412
|
-
|
413
|
-
<option value="1">Lisbon</option>
|
414
|
-
<option value="2">Madrid</option>
|
415
|
-
...
|
416
|
-
```
|
417
|
-
|
418
|
-
The first argument to `options_for_select` 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.
|
419
|
-
|
420
|
-
Knowing this, you can combine `select_tag` and `options_for_select` to achieve the desired, complete markup:
|
421
|
-
|
422
|
-
```erb
|
423
|
-
<%= select_tag(:city_id, options_for_select(...)) %>
|
424
|
-
```
|
425
|
-
|
426
|
-
`options_for_select` allows you to pre-select an option by passing its value.
|
427
|
-
|
428
|
-
```html+erb
|
429
|
-
<%= options_for_select([['Lisbon', 1], ['Madrid', 2], ...], 2) %>
|
430
|
-
|
431
|
-
output:
|
432
|
-
|
433
|
-
<option value="1">Lisbon</option>
|
434
|
-
<option value="2" selected="selected">Madrid</option>
|
435
|
-
...
|
436
|
-
```
|
437
|
-
|
438
|
-
Whenever Rails sees that the internal value of an option being generated matches this value, it will add the `selected` attribute to that option.
|
439
|
-
|
440
|
-
TIP: The second argument to `options_for_select` must be exactly equal to the desired internal value. In particular if the value is the integer `2` you cannot pass `"2"` to `options_for_select` - you must pass `2`. Be aware of values extracted from the `params` hash as they are all strings.
|
441
|
-
|
442
|
-
WARNING: when `:include_blank` or `:prompt` are not present, `:include_blank` is forced true if the select attribute `required` is true, display `size` is one and `multiple` is not true.
|
443
|
-
|
444
|
-
You can add arbitrary attributes to the options using hashes:
|
445
|
-
|
446
|
-
```html+erb
|
447
|
-
<%= options_for_select(
|
448
|
-
[
|
449
|
-
['Lisbon', 1, { 'data-size' => '2.8 million' }],
|
450
|
-
['Madrid', 2, { 'data-size' => '3.2 million' }]
|
451
|
-
], 2
|
452
|
-
) %>
|
453
|
-
|
454
|
-
output:
|
455
|
-
|
456
|
-
<option value="1" data-size="2.8 million">Lisbon</option>
|
457
|
-
<option value="2" selected="selected" data-size="3.2 million">Madrid</option>
|
458
|
-
...
|
459
|
-
```
|
460
|
-
|
461
|
-
### Select Boxes for Dealing with Models
|
462
|
-
|
463
|
-
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 `_tag` suffix from `select_tag`:
|
464
|
-
|
465
|
-
```ruby
|
466
|
-
# controller:
|
467
|
-
@person = Person.new(city_id: 2)
|
468
|
-
```
|
469
|
-
|
470
|
-
```erb
|
471
|
-
# view:
|
472
|
-
<%= select(:person, :city_id, [['Lisbon', 1], ['Madrid', 2], ...]) %>
|
473
|
-
```
|
474
|
-
|
475
|
-
Notice that the third parameter, the options array, is the same kind of argument you pass to `options_for_select`. 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 `@person.city_id` attribute.
|
476
|
-
|
477
|
-
As with other helpers, if you were to use the `select` helper on a form builder scoped to the `@person` object, the syntax would be:
|
478
|
-
|
479
|
-
```erb
|
480
|
-
# select on a form builder
|
481
|
-
<%= f.select(:city_id, ...) %>
|
482
|
-
```
|
483
|
-
|
484
|
-
You can also pass a block to `select` helper:
|
485
|
-
|
486
|
-
```erb
|
487
|
-
<%= f.select(:city_id) do %>
|
488
|
-
<% [['Lisbon', 1], ['Madrid', 2]].each do |c| -%>
|
489
|
-
<%= content_tag(:option, c.first, value: c.last) %>
|
490
|
-
<% end %>
|
491
|
-
<% end %>
|
492
|
-
```
|
493
|
-
|
494
|
-
WARNING: If you are using `select` (or similar helpers such as `collection_select`, `select_tag`) to set a `belongs_to` association you must pass the name of the foreign key (in the example above `city_id`), not the name of association itself. If you specify `city` instead of `city_id` Active Record will raise an error along the lines of `ActiveRecord::AssociationTypeMismatch: City(#17815740) expected, got String(#1138750)` when you pass the `params` hash to `Person.new` or `update`. 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.
|
495
|
-
|
496
|
-
### Option Tags from a Collection of Arbitrary Objects
|
497
|
-
|
498
|
-
Generating options tags with `options_for_select` 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:
|
499
|
-
|
500
|
-
```erb
|
501
|
-
<% cities_array = City.all.map { |city| [city.name, city.id] } %>
|
502
|
-
<%= options_for_select(cities_array) %>
|
503
|
-
```
|
504
|
-
|
505
|
-
This is a perfectly valid solution, but Rails provides a less verbose alternative: `options_from_collection_for_select`. This helper expects a collection of arbitrary objects and two additional arguments: the names of the methods to read the option **value** and **text** from, respectively:
|
506
|
-
|
507
|
-
```erb
|
508
|
-
<%= options_from_collection_for_select(City.all, :id, :name) %>
|
509
|
-
```
|
510
|
-
|
511
|
-
As the name implies, this only generates option tags. To generate a working select box you would need to use it in conjunction with `select_tag`, just as you would with `options_for_select`. When working with model objects, just as `select` combines `select_tag` and `options_for_select`, `collection_select` combines `select_tag` with `options_from_collection_for_select`.
|
512
|
-
|
513
|
-
```erb
|
514
|
-
<%= collection_select(:person, :city_id, City.all, :id, :name) %>
|
515
|
-
```
|
516
|
-
|
517
|
-
As with other helpers, if you were to use the `collection_select` helper on a form builder scoped to the `@person` object, the syntax would be:
|
518
|
-
|
519
|
-
```erb
|
520
|
-
<%= f.collection_select(:city_id, City.all, :id, :name) %>
|
521
|
-
```
|
522
|
-
|
523
|
-
To recap, `options_from_collection_for_select` is to `collection_select` what `options_for_select` is to `select`.
|
524
|
-
|
525
|
-
NOTE: Pairs passed to `options_for_select` should have the name first and the id second, however with `options_from_collection_for_select` the first argument is the value method and the second the text method.
|
526
|
-
|
527
|
-
### Time Zone and Country Select
|
528
|
-
|
529
|
-
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 `collection_select`, but you can simply use the `time_zone_select` helper that already wraps this:
|
530
|
-
|
531
|
-
```erb
|
532
|
-
<%= time_zone_select(:person, :time_zone) %>
|
533
|
-
```
|
534
|
-
|
535
|
-
There is also `time_zone_options_for_select` helper for a more manual (therefore more customizable) way of doing this. Read the API documentation to learn about the possible arguments for these two methods.
|
536
|
-
|
537
|
-
Rails _used_ to have a `country_select` helper for choosing countries, but this has been extracted to the [country_select plugin](https://github.com/stefanpenner/country_select). 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).
|
538
|
-
|
539
|
-
Using Date and Time Form Helpers
|
540
|
-
--------------------------------
|
541
|
-
|
542
|
-
You can choose not to use the form helpers generating HTML5 date and time input fields and use the alternative date and time helpers. These date and time helpers differ from all the other form helpers in two important respects:
|
543
|
-
|
544
|
-
* 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 `params` hash with your date or time.
|
545
|
-
* Other helpers use the `_tag` suffix to indicate whether a helper is a barebones helper or one that operates on model objects. With dates and times, `select_date`, `select_time` and `select_datetime` are the barebones helpers, `date_select`, `time_select` and `datetime_select` are the equivalent model object helpers.
|
546
|
-
|
547
|
-
Both of these families of helpers will create a series of select boxes for the different components (year, month, day etc.).
|
548
|
-
|
549
|
-
### Barebones Helpers
|
550
|
-
|
551
|
-
The `select_*` 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:
|
552
|
-
|
553
|
-
```erb
|
554
|
-
<%= select_date Date.today, prefix: :start_date %>
|
555
|
-
```
|
556
|
-
|
557
|
-
outputs (with actual option values omitted for brevity)
|
558
|
-
|
559
|
-
```html
|
560
|
-
<select id="start_date_year" name="start_date[year]"> ... </select>
|
561
|
-
<select id="start_date_month" name="start_date[month]"> ... </select>
|
562
|
-
<select id="start_date_day" name="start_date[day]"> ... </select>
|
563
|
-
```
|
564
|
-
|
565
|
-
The above inputs would result in `params[:start_date]` being a hash with keys `:year`, `:month`, `:day`. To get an actual `Date`, `Time` or `DateTime` object you would have to extract these values and pass them to the appropriate constructor, for example:
|
566
|
-
|
567
|
-
```ruby
|
568
|
-
Date.civil(params[:start_date][:year].to_i, params[:start_date][:month].to_i, params[:start_date][:day].to_i)
|
569
|
-
```
|
570
|
-
|
571
|
-
The `:prefix` option is the key used to retrieve the hash of date components from the `params` hash. Here it was set to `start_date`, if omitted it will default to `date`.
|
572
|
-
|
573
|
-
### Model Object Helpers
|
574
|
-
|
575
|
-
`select_date` does not work well with forms that update or create Active Record objects as Active Record expects each element of the `params` hash to correspond to one attribute.
|
576
|
-
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:
|
577
|
-
|
578
|
-
```erb
|
579
|
-
<%= date_select :person, :birth_date %>
|
580
|
-
```
|
581
|
-
|
582
|
-
outputs (with actual option values omitted for brevity)
|
583
|
-
|
584
|
-
```html
|
585
|
-
<select id="person_birth_date_1i" name="person[birth_date(1i)]"> ... </select>
|
586
|
-
<select id="person_birth_date_2i" name="person[birth_date(2i)]"> ... </select>
|
587
|
-
<select id="person_birth_date_3i" name="person[birth_date(3i)]"> ... </select>
|
588
|
-
```
|
589
|
-
|
590
|
-
which results in a `params` hash like
|
591
|
-
|
592
|
-
```ruby
|
593
|
-
{'person' => {'birth_date(1i)' => '2008', 'birth_date(2i)' => '11', 'birth_date(3i)' => '22'}}
|
594
|
-
```
|
595
|
-
|
596
|
-
When this is passed to `Person.new` (or `update`), Active Record spots that these parameters should all be used to construct the `birth_date` attribute and uses the suffixed information to determine in which order it should pass these parameters to functions such as `Date.civil`.
|
597
|
-
|
598
|
-
### Common Options
|
599
|
-
|
600
|
-
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 `:start_year` and `:end_year` options override this. For an exhaustive list of the available options, refer to the [API documentation](http://api.rubyonrails.org/classes/ActionView/Helpers/DateHelper.html).
|
601
|
-
|
602
|
-
As a rule of thumb you should be using `date_select` when working with model objects and `select_date` in other cases, such as a search form which filters results by date.
|
603
|
-
|
604
|
-
NOTE: 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.
|
605
|
-
|
606
|
-
### Individual Components
|
607
|
-
|
608
|
-
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 `select_year`, `select_month`, `select_day`, `select_hour`, `select_minute`, `select_second`. These helpers are fairly straightforward. By default they will generate an input field named after the time component (for example, "year" for `select_year`, "month" for `select_month` etc.) although this can be overridden with the `:field_name` option. The `:prefix` option works in the same way that it does for `select_date` and `select_time` and has the same default value.
|
609
|
-
|
610
|
-
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:
|
611
|
-
|
612
|
-
```erb
|
613
|
-
<%= select_year(2009) %>
|
614
|
-
<%= select_year(Time.now) %>
|
615
|
-
```
|
616
|
-
|
617
|
-
will produce the same output if the current year is 2009 and the value chosen by the user can be retrieved by `params[:date][:year]`.
|
618
|
-
|
619
|
-
Uploading Files
|
620
|
-
---------------
|
621
|
-
|
622
|
-
A common task is uploading some sort of file, whether it's a picture of a person or a CSV file containing data to process. The most important thing to remember with file uploads is that the rendered form's encoding **MUST** be set to "multipart/form-data". If you use `form_for`, this is done automatically. If you use `form_tag`, you must set it yourself, as per the following example.
|
623
|
-
|
624
|
-
The following two forms both upload a file.
|
625
|
-
|
626
|
-
```erb
|
627
|
-
<%= form_tag({action: :upload}, multipart: true) do %>
|
628
|
-
<%= file_field_tag 'picture' %>
|
629
|
-
<% end %>
|
630
|
-
|
631
|
-
<%= form_for @person do |f| %>
|
632
|
-
<%= f.file_field :picture %>
|
633
|
-
<% end %>
|
634
|
-
```
|
635
|
-
|
636
|
-
Rails provides the usual pair of helpers: the barebones `file_field_tag` and the model oriented `file_field`. 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 `params[:picture]` and in the second case in `params[:person][:picture]`.
|
637
|
-
|
638
|
-
### What Gets Uploaded
|
639
|
-
|
640
|
-
The object in the `params` 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 `original_filename` attribute containing the name the file had on the user's computer and a `content_type` attribute containing the MIME type of the uploaded file. The following snippet saves the uploaded content in `#{Rails.root}/public/uploads` under the same name as the original file (assuming the form was the one in the previous example).
|
641
|
-
|
642
|
-
```ruby
|
643
|
-
def upload
|
644
|
-
uploaded_io = params[:person][:picture]
|
645
|
-
File.open(Rails.root.join('public', 'uploads', uploaded_io.original_filename), 'wb') do |file|
|
646
|
-
file.write(uploaded_io.read)
|
647
|
-
end
|
648
|
-
end
|
649
|
-
```
|
650
|
-
|
651
|
-
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 [CarrierWave](https://github.com/jnicklas/carrierwave) and [Paperclip](https://github.com/thoughtbot/paperclip).
|
652
|
-
|
653
|
-
NOTE: If the user has not selected a file the corresponding parameter will be an empty string.
|
654
|
-
|
655
|
-
### Dealing with Ajax
|
656
|
-
|
657
|
-
Unlike other forms making an asynchronous file upload form is not as simple as providing `form_for` with `remote: true`. 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.
|
658
|
-
|
659
|
-
Customizing Form Builders
|
660
|
-
-------------------------
|
661
|
-
|
662
|
-
As mentioned previously the object yielded by `form_for` and `fields_for` 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:
|
663
|
-
|
664
|
-
```erb
|
665
|
-
<%= form_for @person do |f| %>
|
666
|
-
<%= text_field_with_label f, :first_name %>
|
667
|
-
<% end %>
|
668
|
-
```
|
669
|
-
|
670
|
-
can be replaced with
|
671
|
-
|
672
|
-
```erb
|
673
|
-
<%= form_for @person, builder: LabellingFormBuilder do |f| %>
|
674
|
-
<%= f.text_field :first_name %>
|
675
|
-
<% end %>
|
676
|
-
```
|
677
|
-
|
678
|
-
by defining a `LabellingFormBuilder` class similar to the following:
|
679
|
-
|
680
|
-
```ruby
|
681
|
-
class LabellingFormBuilder < ActionView::Helpers::FormBuilder
|
682
|
-
def text_field(attribute, options={})
|
683
|
-
label(attribute) + super
|
684
|
-
end
|
685
|
-
end
|
686
|
-
```
|
687
|
-
|
688
|
-
If you reuse this frequently you could define a `labeled_form_for` helper that automatically applies the `builder: LabellingFormBuilder` option.
|
689
|
-
|
690
|
-
The form builder used also determines what happens when you do
|
691
|
-
|
692
|
-
```erb
|
693
|
-
<%= render partial: f %>
|
694
|
-
```
|
695
|
-
|
696
|
-
If `f` is an instance of `FormBuilder` then this will render the `form` partial, setting the partial's object to the form builder. If the form builder is of class `LabellingFormBuilder` then the `labelling_form` partial would be rendered instead.
|
697
|
-
|
698
|
-
Understanding Parameter Naming Conventions
|
699
|
-
------------------------------------------
|
700
|
-
|
701
|
-
As you've seen in the previous sections, values from forms can be at the top level of the `params` hash or nested in another hash. For example, in a standard `create`
|
702
|
-
action for a Person model, `params[:person]` would usually be a hash of all the attributes for the person to create. The `params` hash can also contain arrays, arrays of hashes and so on.
|
703
|
-
|
704
|
-
Fundamentally HTML 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.
|
705
|
-
|
706
|
-
TIP: You may find you can try out examples in this section faster by using the console to directly invoke Rack's parameter parser. For example,
|
707
|
-
|
708
|
-
```ruby
|
709
|
-
Rack::Utils.parse_query "name=fred&phone=0123456789"
|
710
|
-
# => {"name"=>"fred", "phone"=>"0123456789"}
|
711
|
-
```
|
712
|
-
|
713
|
-
### Basic Structures
|
714
|
-
|
715
|
-
The two basic structures are arrays and hashes. Hashes mirror the syntax used for accessing the value in `params`. For example, if a form contains:
|
716
|
-
|
717
|
-
```html
|
718
|
-
<input id="person_name" name="person[name]" type="text" value="Henry"/>
|
719
|
-
```
|
720
|
-
|
721
|
-
the `params` hash will contain
|
722
|
-
|
723
|
-
```erb
|
724
|
-
{'person' => {'name' => 'Henry'}}
|
725
|
-
```
|
726
|
-
|
727
|
-
and `params[:person][:name]` will retrieve the submitted value in the controller.
|
728
|
-
|
729
|
-
Hashes can be nested as many levels as required, for example:
|
730
|
-
|
731
|
-
```html
|
732
|
-
<input id="person_address_city" name="person[address][city]" type="text" value="New York"/>
|
733
|
-
```
|
734
|
-
|
735
|
-
will result in the `params` hash being
|
736
|
-
|
737
|
-
```ruby
|
738
|
-
{'person' => {'address' => {'city' => 'New York'}}}
|
739
|
-
```
|
740
|
-
|
741
|
-
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 users to be able to input multiple phone numbers, you could place this in the form:
|
742
|
-
|
743
|
-
```html
|
744
|
-
<input name="person[phone_number][]" type="text"/>
|
745
|
-
<input name="person[phone_number][]" type="text"/>
|
746
|
-
<input name="person[phone_number][]" type="text"/>
|
747
|
-
```
|
748
|
-
|
749
|
-
This would result in `params[:person][:phone_number]` being an array containing the inputted phone numbers.
|
750
|
-
|
751
|
-
### Combining Them
|
752
|
-
|
753
|
-
We can mix and match these two concepts. 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
|
754
|
-
|
755
|
-
```html
|
756
|
-
<input name="addresses[][line1]" type="text"/>
|
757
|
-
<input name="addresses[][line2]" type="text"/>
|
758
|
-
<input name="addresses[][city]" type="text"/>
|
759
|
-
```
|
760
|
-
|
761
|
-
This would result in `params[:addresses]` being an array of hashes with keys `line1`, `line2` and `city`. Rails decides to start accumulating values in a new hash whenever it encounters an input name that already exists in the current hash.
|
762
|
-
|
763
|
-
There's a restriction, however, while hashes can be nested arbitrarily, only one level of "arrayness" is allowed. Arrays can usually be 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.
|
764
|
-
|
765
|
-
WARNING: Array parameters do not play well with the `check_box` helper. According to the HTML specification unchecked checkboxes submit no value. However it is often convenient for a checkbox to always submit a value. The `check_box` 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 `check_box_tag` or to use hashes instead of arrays.
|
766
|
-
|
767
|
-
### Using Form Helpers
|
768
|
-
|
769
|
-
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 `text_field_tag` Rails also provides higher level support. The two tools at your disposal here are the name parameter to `form_for` and `fields_for` and the `:index` option that helpers take.
|
770
|
-
|
771
|
-
You might want to render a form with a set of edit fields for each of a person's addresses. For example:
|
772
|
-
|
773
|
-
```erb
|
774
|
-
<%= form_for @person do |person_form| %>
|
775
|
-
<%= person_form.text_field :name %>
|
776
|
-
<% @person.addresses.each do |address| %>
|
777
|
-
<%= person_form.fields_for address, index: address.id do |address_form|%>
|
778
|
-
<%= address_form.text_field :city %>
|
779
|
-
<% end %>
|
780
|
-
<% end %>
|
781
|
-
<% end %>
|
782
|
-
```
|
783
|
-
|
784
|
-
Assuming the person had two addresses, with ids 23 and 45 this would create output similar to this:
|
785
|
-
|
786
|
-
```html
|
787
|
-
<form accept-charset="UTF-8" action="/people/1" class="edit_person" id="edit_person_1" method="post">
|
788
|
-
<input id="person_name" name="person[name]" type="text" />
|
789
|
-
<input id="person_address_23_city" name="person[address][23][city]" type="text" />
|
790
|
-
<input id="person_address_45_city" name="person[address][45][city]" type="text" />
|
791
|
-
</form>
|
792
|
-
```
|
793
|
-
|
794
|
-
This will result in a `params` hash that looks like
|
795
|
-
|
796
|
-
```ruby
|
797
|
-
{'person' => {'name' => 'Bob', 'address' => {'23' => {'city' => 'Paris'}, '45' => {'city' => 'London'}}}}
|
798
|
-
```
|
799
|
-
|
800
|
-
Rails knows that all these inputs should be part of the person hash because you
|
801
|
-
called `fields_for` on the first form builder. By specifying an `:index` option
|
802
|
-
you're telling Rails that instead of naming the inputs `person[address][city]`
|
803
|
-
it should insert that index surrounded by [] between the address and the city.
|
804
|
-
This is often useful as it is then easy to locate which Address record
|
805
|
-
should be modified. You can pass numbers with some other significance,
|
806
|
-
strings or even `nil` (which will result in an array parameter being created).
|
807
|
-
|
808
|
-
To create more intricate nestings, you can specify the first part of the input
|
809
|
-
name (`person[address]` in the previous example) explicitly:
|
810
|
-
|
811
|
-
```erb
|
812
|
-
<%= fields_for 'person[address][primary]', address, index: address do |address_form| %>
|
813
|
-
<%= address_form.text_field :city %>
|
814
|
-
<% end %>
|
815
|
-
```
|
816
|
-
|
817
|
-
will create inputs like
|
818
|
-
|
819
|
-
```html
|
820
|
-
<input id="person_address_primary_1_city" name="person[address][primary][1][city]" type="text" value="bologna" />
|
821
|
-
```
|
822
|
-
|
823
|
-
As a general rule the final input name is the concatenation of the name given to `fields_for`/`form_for`, the index value and the name of the attribute. You can also pass an `:index` option directly to helpers such as `text_field`, but it is usually less repetitive to specify this at the form builder level rather than on individual input controls.
|
824
|
-
|
825
|
-
As a shortcut you can append [] to the name and omit the `:index` option. This is the same as specifying `index: address` so
|
826
|
-
|
827
|
-
```erb
|
828
|
-
<%= fields_for 'person[address][primary][]', address do |address_form| %>
|
829
|
-
<%= address_form.text_field :city %>
|
830
|
-
<% end %>
|
831
|
-
```
|
832
|
-
|
833
|
-
produces exactly the same output as the previous example.
|
834
|
-
|
835
|
-
Forms to External Resources
|
836
|
-
---------------------------
|
837
|
-
|
838
|
-
Rails' form helpers can also be used to build a form for posting data to an external resource. However, at times it can be necessary to set an `authenticity_token` for the resource; this can be done by passing an `authenticity_token: 'your_external_token'` parameter to the `form_tag` options:
|
839
|
-
|
840
|
-
```erb
|
841
|
-
<%= form_tag 'http://farfar.away/form', authenticity_token: 'external_token' do %>
|
842
|
-
Form contents
|
843
|
-
<% end %>
|
844
|
-
```
|
845
|
-
|
846
|
-
Sometimes when submitting data to an external resource, like a payment gateway, the fields that can be used in the form are limited by an external API and it may be undesirable to generate an `authenticity_token`. To not send a token, simply pass `false` to the `:authenticity_token` option:
|
847
|
-
|
848
|
-
```erb
|
849
|
-
<%= form_tag 'http://farfar.away/form', authenticity_token: false do %>
|
850
|
-
Form contents
|
851
|
-
<% end %>
|
852
|
-
```
|
853
|
-
|
854
|
-
The same technique is also available for `form_for`:
|
855
|
-
|
856
|
-
```erb
|
857
|
-
<%= form_for @invoice, url: external_url, authenticity_token: 'external_token' do |f| %>
|
858
|
-
Form contents
|
859
|
-
<% end %>
|
860
|
-
```
|
861
|
-
|
862
|
-
Or if you don't want to render an `authenticity_token` field:
|
863
|
-
|
864
|
-
```erb
|
865
|
-
<%= form_for @invoice, url: external_url, authenticity_token: false do |f| %>
|
866
|
-
Form contents
|
867
|
-
<% end %>
|
868
|
-
```
|
869
|
-
|
870
|
-
Building Complex Forms
|
871
|
-
----------------------
|
872
|
-
|
873
|
-
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.
|
874
|
-
|
875
|
-
### Configuring the Model
|
876
|
-
|
877
|
-
Active Record provides model level support via the `accepts_nested_attributes_for` method:
|
878
|
-
|
879
|
-
```ruby
|
880
|
-
class Person < ActiveRecord::Base
|
881
|
-
has_many :addresses
|
882
|
-
accepts_nested_attributes_for :addresses
|
883
|
-
end
|
884
|
-
|
885
|
-
class Address < ActiveRecord::Base
|
886
|
-
belongs_to :person
|
887
|
-
end
|
888
|
-
```
|
889
|
-
|
890
|
-
This creates an `addresses_attributes=` method on `Person` that allows you to create, update and (optionally) destroy addresses.
|
891
|
-
|
892
|
-
### Nested Forms
|
893
|
-
|
894
|
-
The following form allows a user to create a `Person` and its associated addresses.
|
895
|
-
|
896
|
-
```html+erb
|
897
|
-
<%= form_for @person do |f| %>
|
898
|
-
Addresses:
|
899
|
-
<ul>
|
900
|
-
<%= f.fields_for :addresses do |addresses_form| %>
|
901
|
-
<li>
|
902
|
-
<%= addresses_form.label :kind %>
|
903
|
-
<%= addresses_form.text_field :kind %>
|
904
|
-
|
905
|
-
<%= addresses_form.label :street %>
|
906
|
-
<%= addresses_form.text_field :street %>
|
907
|
-
...
|
908
|
-
</li>
|
909
|
-
<% end %>
|
910
|
-
</ul>
|
911
|
-
<% end %>
|
912
|
-
```
|
913
|
-
|
914
|
-
|
915
|
-
When an association accepts nested attributes `fields_for` renders its block once for every element of the association. In particular, if a person has no addresses it renders nothing. A common pattern is for the controller to build one or more empty children so that at least one set of fields is shown to the user. The example below would result in 2 sets of address fields being rendered on the new person form.
|
916
|
-
|
917
|
-
```ruby
|
918
|
-
def new
|
919
|
-
@person = Person.new
|
920
|
-
2.times { @person.addresses.build}
|
921
|
-
end
|
922
|
-
```
|
923
|
-
|
924
|
-
The `fields_for` yields a form builder. The parameters' name will be what
|
925
|
-
`accepts_nested_attributes_for` expects. For example, when creating a user with
|
926
|
-
2 addresses, the submitted parameters would look like:
|
927
|
-
|
928
|
-
```ruby
|
929
|
-
{
|
930
|
-
'person' => {
|
931
|
-
'name' => 'John Doe',
|
932
|
-
'addresses_attributes' => {
|
933
|
-
'0' => {
|
934
|
-
'kind' => 'Home',
|
935
|
-
'street' => '221b Baker Street'
|
936
|
-
},
|
937
|
-
'1' => {
|
938
|
-
'kind' => 'Office',
|
939
|
-
'street' => '31 Spooner Street'
|
940
|
-
}
|
941
|
-
}
|
942
|
-
}
|
943
|
-
}
|
944
|
-
```
|
945
|
-
|
946
|
-
The keys of the `:addresses_attributes` hash are unimportant, they need merely be different for each address.
|
947
|
-
|
948
|
-
If the associated object is already saved, `fields_for` autogenerates a hidden input with the `id` of the saved record. You can disable this by passing `include_id: false` to `fields_for`. You may wish to do this if the autogenerated input is placed in a location where an input tag is not valid HTML or when using an ORM where children do not have an `id`.
|
949
|
-
|
950
|
-
### The Controller
|
951
|
-
|
952
|
-
As usual you need to
|
953
|
-
[whitelist the parameters](action_controller_overview.html#strong-parameters) in
|
954
|
-
the controller before you pass them to the model:
|
955
|
-
|
956
|
-
```ruby
|
957
|
-
def create
|
958
|
-
@person = Person.new(person_params)
|
959
|
-
# ...
|
960
|
-
end
|
961
|
-
|
962
|
-
private
|
963
|
-
def person_params
|
964
|
-
params.require(:person).permit(:name, addresses_attributes: [:id, :kind, :street])
|
965
|
-
end
|
966
|
-
```
|
967
|
-
|
968
|
-
### Removing Objects
|
969
|
-
|
970
|
-
You can allow users to delete associated objects by passing `allow_destroy: true` to `accepts_nested_attributes_for`
|
971
|
-
|
972
|
-
```ruby
|
973
|
-
class Person < ActiveRecord::Base
|
974
|
-
has_many :addresses
|
975
|
-
accepts_nested_attributes_for :addresses, allow_destroy: true
|
976
|
-
end
|
977
|
-
```
|
978
|
-
|
979
|
-
If the hash of attributes for an object contains the key `_destroy` with a value
|
980
|
-
of `1` or `true` then the object will be destroyed. This form allows users to
|
981
|
-
remove addresses:
|
982
|
-
|
983
|
-
```erb
|
984
|
-
<%= form_for @person do |f| %>
|
985
|
-
Addresses:
|
986
|
-
<ul>
|
987
|
-
<%= f.fields_for :addresses do |addresses_form| %>
|
988
|
-
<li>
|
989
|
-
<%= addresses_form.check_box :_destroy%>
|
990
|
-
<%= addresses_form.label :kind %>
|
991
|
-
<%= addresses_form.text_field :kind %>
|
992
|
-
...
|
993
|
-
</li>
|
994
|
-
<% end %>
|
995
|
-
</ul>
|
996
|
-
<% end %>
|
997
|
-
```
|
998
|
-
|
999
|
-
Don't forget to update the whitelisted params in your controller to also include
|
1000
|
-
the `_destroy` field:
|
1001
|
-
|
1002
|
-
```ruby
|
1003
|
-
def person_params
|
1004
|
-
params.require(:person).
|
1005
|
-
permit(:name, addresses_attributes: [:id, :kind, :street, :_destroy])
|
1006
|
-
end
|
1007
|
-
```
|
1008
|
-
|
1009
|
-
### Preventing Empty Records
|
1010
|
-
|
1011
|
-
It is often useful to ignore sets of fields that the user has not filled in. You can control this by passing a `:reject_if` proc to `accepts_nested_attributes_for`. This proc will be called with each hash of attributes submitted by the form. If the proc returns `false` then Active Record will not build an associated object for that hash. The example below only tries to build an address if the `kind` attribute is set.
|
1012
|
-
|
1013
|
-
```ruby
|
1014
|
-
class Person < ActiveRecord::Base
|
1015
|
-
has_many :addresses
|
1016
|
-
accepts_nested_attributes_for :addresses, reject_if: lambda {|attributes| attributes['kind'].blank?}
|
1017
|
-
end
|
1018
|
-
```
|
1019
|
-
|
1020
|
-
As a convenience you can instead pass the symbol `:all_blank` which will create a proc that will reject records where all the attributes are blank excluding any value for `_destroy`.
|
1021
|
-
|
1022
|
-
### Adding Fields on the Fly
|
1023
|
-
|
1024
|
-
Rather than rendering multiple sets of fields ahead of time you may wish to add them only when a user clicks on an 'Add new address' button. Rails does not provide any built-in support for this. When generating new sets of fields you must ensure the key of the associated array is unique - the current JavaScript date (milliseconds after the epoch) is a common choice.
|