rails 4.1.14.2 → 5.2.4.4
Sign up to get free protection for your applications and to get access to all the features.
Potentially problematic release.
This version of rails might be problematic. Click here for more details.
- checksums.yaml +5 -5
- data/README.md +33 -19
- metadata +65 -313
- data/guides/CHANGELOG.md +0 -106
- data/guides/Rakefile +0 -77
- 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 -53
- 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 -710
- 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 -53
- 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/code/getting_started/Gemfile +0 -40
- data/guides/code/getting_started/Gemfile.lock +0 -125
- data/guides/code/getting_started/README.rdoc +0 -28
- data/guides/code/getting_started/Rakefile +0 -6
- data/guides/code/getting_started/app/assets/javascripts/application.js +0 -15
- data/guides/code/getting_started/app/assets/javascripts/comments.js.coffee +0 -3
- data/guides/code/getting_started/app/assets/javascripts/posts.js.coffee +0 -3
- data/guides/code/getting_started/app/assets/javascripts/welcome.js.coffee +0 -3
- data/guides/code/getting_started/app/assets/stylesheets/application.css +0 -13
- data/guides/code/getting_started/app/assets/stylesheets/comments.css.scss +0 -3
- data/guides/code/getting_started/app/assets/stylesheets/posts.css.scss +0 -3
- data/guides/code/getting_started/app/assets/stylesheets/welcome.css.scss +0 -3
- data/guides/code/getting_started/app/controllers/application_controller.rb +0 -5
- data/guides/code/getting_started/app/controllers/comments_controller.rb +0 -23
- data/guides/code/getting_started/app/controllers/posts_controller.rb +0 -53
- data/guides/code/getting_started/app/controllers/welcome_controller.rb +0 -4
- data/guides/code/getting_started/app/helpers/application_helper.rb +0 -2
- data/guides/code/getting_started/app/helpers/comments_helper.rb +0 -2
- data/guides/code/getting_started/app/helpers/posts_helper.rb +0 -2
- data/guides/code/getting_started/app/helpers/welcome_helper.rb +0 -2
- data/guides/code/getting_started/app/models/comment.rb +0 -3
- data/guides/code/getting_started/app/models/post.rb +0 -7
- data/guides/code/getting_started/app/views/comments/_comment.html.erb +0 -15
- data/guides/code/getting_started/app/views/comments/_form.html.erb +0 -13
- data/guides/code/getting_started/app/views/layouts/application.html.erb +0 -14
- data/guides/code/getting_started/app/views/posts/_form.html.erb +0 -27
- data/guides/code/getting_started/app/views/posts/edit.html.erb +0 -5
- data/guides/code/getting_started/app/views/posts/index.html.erb +0 -21
- data/guides/code/getting_started/app/views/posts/new.html.erb +0 -5
- data/guides/code/getting_started/app/views/posts/show.html.erb +0 -18
- data/guides/code/getting_started/app/views/welcome/index.html.erb +0 -4
- data/guides/code/getting_started/bin/bundle +0 -4
- data/guides/code/getting_started/bin/rails +0 -4
- data/guides/code/getting_started/bin/rake +0 -4
- data/guides/code/getting_started/config.ru +0 -4
- data/guides/code/getting_started/config/application.rb +0 -18
- data/guides/code/getting_started/config/boot.rb +0 -4
- data/guides/code/getting_started/config/database.yml +0 -25
- data/guides/code/getting_started/config/environment.rb +0 -5
- data/guides/code/getting_started/config/environments/development.rb +0 -30
- data/guides/code/getting_started/config/environments/production.rb +0 -80
- data/guides/code/getting_started/config/environments/test.rb +0 -36
- data/guides/code/getting_started/config/initializers/backtrace_silencers.rb +0 -7
- data/guides/code/getting_started/config/initializers/filter_parameter_logging.rb +0 -4
- data/guides/code/getting_started/config/initializers/inflections.rb +0 -16
- data/guides/code/getting_started/config/initializers/locale.rb +0 -9
- data/guides/code/getting_started/config/initializers/mime_types.rb +0 -5
- data/guides/code/getting_started/config/initializers/secret_token.rb +0 -12
- data/guides/code/getting_started/config/initializers/session_store.rb +0 -3
- data/guides/code/getting_started/config/initializers/wrap_parameters.rb +0 -14
- data/guides/code/getting_started/config/locales/en.yml +0 -23
- data/guides/code/getting_started/config/routes.rb +0 -7
- data/guides/code/getting_started/db/migrate/20130122042648_create_posts.rb +0 -10
- data/guides/code/getting_started/db/migrate/20130122045842_create_comments.rb +0 -11
- data/guides/code/getting_started/db/schema.rb +0 -33
- data/guides/code/getting_started/db/seeds.rb +0 -7
- data/guides/code/getting_started/public/404.html +0 -60
- data/guides/code/getting_started/public/422.html +0 -60
- data/guides/code/getting_started/public/500.html +0 -59
- data/guides/code/getting_started/public/favicon.ico +0 -0
- data/guides/code/getting_started/public/robots.txt +0 -5
- data/guides/code/getting_started/test/controllers/comments_controller_test.rb +0 -7
- data/guides/code/getting_started/test/controllers/posts_controller_test.rb +0 -7
- data/guides/code/getting_started/test/controllers/welcome_controller_test.rb +0 -9
- data/guides/code/getting_started/test/fixtures/comments.yml +0 -11
- data/guides/code/getting_started/test/fixtures/posts.yml +0 -9
- data/guides/code/getting_started/test/helpers/comments_helper_test.rb +0 -4
- data/guides/code/getting_started/test/helpers/posts_helper_test.rb +0 -4
- data/guides/code/getting_started/test/helpers/welcome_helper_test.rb +0 -4
- data/guides/code/getting_started/test/models/comment_test.rb +0 -7
- data/guides/code/getting_started/test/models/post_test.rb +0 -7
- data/guides/code/getting_started/test/test_helper.rb +0 -12
- 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 -31
- data/guides/rails_guides/markdown.rb +0 -163
- 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 -556
- data/guides/source/3_2_release_notes.md +0 -565
- data/guides/source/4_0_release_notes.md +0 -276
- data/guides/source/4_1_release_notes.md +0 -731
- data/guides/source/_license.html.erb +0 -2
- data/guides/source/_welcome.html.erb +0 -25
- data/guides/source/action_controller_overview.md +0 -1175
- data/guides/source/action_mailer_basics.md +0 -689
- data/guides/source/action_view_overview.md +0 -1602
- data/guides/source/active_model_basics.md +0 -200
- data/guides/source/active_record_basics.md +0 -373
- data/guides/source/active_record_callbacks.md +0 -410
- data/guides/source/active_record_querying.md +0 -1785
- data/guides/source/active_record_validations.md +0 -1169
- data/guides/source/active_support_core_extensions.md +0 -3817
- data/guides/source/active_support_instrumentation.md +0 -496
- data/guides/source/api_documentation_guidelines.md +0 -315
- data/guides/source/asset_pipeline.md +0 -1165
- data/guides/source/association_basics.md +0 -2229
- data/guides/source/caching_with_rails.md +0 -354
- data/guides/source/command_line.md +0 -603
- data/guides/source/configuring.md +0 -942
- data/guides/source/contributing_to_ruby_on_rails.md +0 -544
- data/guides/source/credits.html.erb +0 -80
- data/guides/source/debugging_rails_applications.md +0 -707
- data/guides/source/development_dependencies_install.md +0 -278
- data/guides/source/documents.yaml +0 -193
- data/guides/source/engines.md +0 -1412
- data/guides/source/form_helpers.md +0 -1001
- data/guides/source/generators.md +0 -663
- data/guides/source/getting_started.md +0 -1946
- data/guides/source/i18n.md +0 -1043
- data/guides/source/index.html.erb +0 -27
- data/guides/source/initialization.md +0 -657
- 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 -146
- data/guides/source/layouts_and_rendering.md +0 -1226
- data/guides/source/maintenance_policy.md +0 -75
- data/guides/source/migrations.md +0 -1143
- data/guides/source/nested_model_forms.md +0 -225
- data/guides/source/plugins.md +0 -444
- data/guides/source/rails_application_templates.md +0 -248
- data/guides/source/rails_on_rack.md +0 -332
- data/guides/source/routing.md +0 -1115
- data/guides/source/ruby_on_rails_guides_guidelines.md +0 -128
- data/guides/source/security.md +0 -1018
- data/guides/source/testing.md +0 -1052
- data/guides/source/upgrading_ruby_on_rails.md +0 -928
- data/guides/source/working_with_javascript_in_rails.md +0 -405
- data/guides/w3c_validator.rb +0 -95
@@ -1,1001 +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 form control naming and their numerous attributes. Rails does 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.
|
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 creation and editing of specific database records.
|
10
|
-
* How to generate select boxes from multiple types of data.
|
11
|
-
* The date and time helpers Rails provides.
|
12
|
-
* What makes a file upload form different.
|
13
|
-
* Some cases of building forms to external resources.
|
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
|
-
|
21
|
-
Dealing with Basic Forms
|
22
|
-
------------------------
|
23
|
-
|
24
|
-
The most basic form helper is `form_tag`.
|
25
|
-
|
26
|
-
```erb
|
27
|
-
<%= form_tag do %>
|
28
|
-
Form contents
|
29
|
-
<% end %>
|
30
|
-
```
|
31
|
-
|
32
|
-
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):
|
33
|
-
|
34
|
-
```html
|
35
|
-
<form accept-charset="UTF-8" action="/home/index" method="post">
|
36
|
-
<div style="margin:0;padding:0">
|
37
|
-
<input name="utf8" type="hidden" value="✓" />
|
38
|
-
<input name="authenticity_token" type="hidden" value="f755bb0ed134b76c432144748a6d4b7a7ddf2b71" />
|
39
|
-
</div>
|
40
|
-
Form contents
|
41
|
-
</form>
|
42
|
-
```
|
43
|
-
|
44
|
-
Now, you'll notice that the HTML contains something extra: a `div` 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 `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).
|
45
|
-
|
46
|
-
NOTE: Throughout this guide, the `div` with the hidden input elements will be excluded from code samples for brevity.
|
47
|
-
|
48
|
-
### A Generic Search Form
|
49
|
-
|
50
|
-
One of the most basic forms you see on the web is a search form. This form contains:
|
51
|
-
|
52
|
-
* a form element with "GET" method,
|
53
|
-
* a label for the input,
|
54
|
-
* a text input element, and
|
55
|
-
* a submit element.
|
56
|
-
|
57
|
-
To create this form you will use `form_tag`, `label_tag`, `text_field_tag`, and `submit_tag`, respectively. Like this:
|
58
|
-
|
59
|
-
```erb
|
60
|
-
<%= form_tag("/search", method: "get") do %>
|
61
|
-
<%= label_tag(:q, "Search for:") %>
|
62
|
-
<%= text_field_tag(:q) %>
|
63
|
-
<%= submit_tag("Search") %>
|
64
|
-
<% end %>
|
65
|
-
```
|
66
|
-
|
67
|
-
This will generate the following HTML:
|
68
|
-
|
69
|
-
```html
|
70
|
-
<form accept-charset="UTF-8" action="/search" method="get"><div style="margin:0;padding:0;display:inline"><input name="utf8" type="hidden" value="✓" /></div>
|
71
|
-
<label for="q">Search for:</label>
|
72
|
-
<input id="q" name="q" type="text" />
|
73
|
-
<input name="commit" type="submit" value="Search" />
|
74
|
-
</form>
|
75
|
-
```
|
76
|
-
|
77
|
-
TIP: For every form input, an ID attribute is generated from its name ("q" in the example). These IDs can be very useful for CSS styling or manipulation of form controls with JavaScript.
|
78
|
-
|
79
|
-
Besides `text_field_tag` and `submit_tag`, there is a similar helper for _every_ form control in HTML.
|
80
|
-
|
81
|
-
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.
|
82
|
-
|
83
|
-
### Multiple Hashes in Form Helper Calls
|
84
|
-
|
85
|
-
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.
|
86
|
-
|
87
|
-
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:
|
88
|
-
|
89
|
-
```ruby
|
90
|
-
form_tag(controller: "people", action: "search", method: "get", class: "nifty_form")
|
91
|
-
# => '<form accept-charset="UTF-8" action="/people/search?method=get&class=nifty_form" method="post">'
|
92
|
-
```
|
93
|
-
|
94
|
-
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:
|
95
|
-
|
96
|
-
```ruby
|
97
|
-
form_tag({controller: "people", action: "search"}, method: "get", class: "nifty_form")
|
98
|
-
# => '<form accept-charset="UTF-8" action="/people/search" method="get" class="nifty_form">'
|
99
|
-
```
|
100
|
-
|
101
|
-
### Helpers for Generating Form Elements
|
102
|
-
|
103
|
-
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 `text_field_tag` and `check_box_tag`), generate just a single `<input>` 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 `params` hash in the controller with the value entered by the user for that field. For example, if the form contains `<%= text_field_tag(:query) %>`, then you would be able to get the value of this field in the controller with `params[:query]`.
|
104
|
-
|
105
|
-
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).
|
106
|
-
|
107
|
-
#### Checkboxes
|
108
|
-
|
109
|
-
Checkboxes are form controls that give the user a set of options they can enable or disable:
|
110
|
-
|
111
|
-
```erb
|
112
|
-
<%= check_box_tag(:pet_dog) %>
|
113
|
-
<%= label_tag(:pet_dog, "I own a dog") %>
|
114
|
-
<%= check_box_tag(:pet_cat) %>
|
115
|
-
<%= label_tag(:pet_cat, "I own a cat") %>
|
116
|
-
```
|
117
|
-
|
118
|
-
This generates the following:
|
119
|
-
|
120
|
-
```html
|
121
|
-
<input id="pet_dog" name="pet_dog" type="checkbox" value="1" />
|
122
|
-
<label for="pet_dog">I own a dog</label>
|
123
|
-
<input id="pet_cat" name="pet_cat" type="checkbox" value="1" />
|
124
|
-
<label for="pet_cat">I own a cat</label>
|
125
|
-
```
|
126
|
-
|
127
|
-
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.
|
128
|
-
|
129
|
-
#### Radio Buttons
|
130
|
-
|
131
|
-
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):
|
132
|
-
|
133
|
-
```erb
|
134
|
-
<%= radio_button_tag(:age, "child") %>
|
135
|
-
<%= label_tag(:age_child, "I am younger than 21") %>
|
136
|
-
<%= radio_button_tag(:age, "adult") %>
|
137
|
-
<%= label_tag(:age_adult, "I'm over 21") %>
|
138
|
-
```
|
139
|
-
|
140
|
-
Output:
|
141
|
-
|
142
|
-
```html
|
143
|
-
<input id="age_child" name="age" type="radio" value="child" />
|
144
|
-
<label for="age_child">I am younger than 21</label>
|
145
|
-
<input id="age_adult" name="age" type="radio" value="adult" />
|
146
|
-
<label for="age_adult">I'm over 21</label>
|
147
|
-
```
|
148
|
-
|
149
|
-
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, and `params[:age]` will contain either "child" or "adult".
|
150
|
-
|
151
|
-
NOTE: Always use labels for checkbox and radio buttons. They associate text with a specific option and,
|
152
|
-
by expanding the clickable region,
|
153
|
-
make it easier for users to click the inputs.
|
154
|
-
|
155
|
-
### Other Helpers of Interest
|
156
|
-
|
157
|
-
Other form controls worth mentioning are textareas, password fields,
|
158
|
-
hidden fields, search fields, telephone fields, date fields, time fields,
|
159
|
-
color fields, datetime fields, datetime-local fields, month fields, week fields,
|
160
|
-
URL fields, email fields, number fields and range fields:
|
161
|
-
|
162
|
-
```erb
|
163
|
-
<%= text_area_tag(:message, "Hi, nice site", size: "24x6") %>
|
164
|
-
<%= password_field_tag(:password) %>
|
165
|
-
<%= hidden_field_tag(:parent_id, "5") %>
|
166
|
-
<%= search_field(:user, :name) %>
|
167
|
-
<%= telephone_field(:user, :phone) %>
|
168
|
-
<%= date_field(:user, :born_on) %>
|
169
|
-
<%= datetime_field(:user, :meeting_time) %>
|
170
|
-
<%= datetime_local_field(:user, :graduation_day) %>
|
171
|
-
<%= month_field(:user, :birthday_month) %>
|
172
|
-
<%= week_field(:user, :birthday_week) %>
|
173
|
-
<%= url_field(:user, :homepage) %>
|
174
|
-
<%= email_field(:user, :address) %>
|
175
|
-
<%= color_field(:user, :favorite_color) %>
|
176
|
-
<%= time_field(:task, :started_at) %>
|
177
|
-
<%= number_field(:product, :price, in: 1.0..20.0, step: 0.5) %>
|
178
|
-
<%= range_field(:product, :discount, in: 1..100) %>
|
179
|
-
```
|
180
|
-
|
181
|
-
Output:
|
182
|
-
|
183
|
-
```html
|
184
|
-
<textarea id="message" name="message" cols="24" rows="6">Hi, nice site</textarea>
|
185
|
-
<input id="password" name="password" type="password" />
|
186
|
-
<input id="parent_id" name="parent_id" type="hidden" value="5" />
|
187
|
-
<input id="user_name" name="user[name]" type="search" />
|
188
|
-
<input id="user_phone" name="user[phone]" type="tel" />
|
189
|
-
<input id="user_born_on" name="user[born_on]" type="date" />
|
190
|
-
<input id="user_meeting_time" name="user[meeting_time]" type="datetime" />
|
191
|
-
<input id="user_graduation_day" name="user[graduation_day]" type="datetime-local" />
|
192
|
-
<input id="user_birthday_month" name="user[birthday_month]" type="month" />
|
193
|
-
<input id="user_birthday_week" name="user[birthday_week]" type="week" />
|
194
|
-
<input id="user_homepage" name="user[homepage]" type="url" />
|
195
|
-
<input id="user_address" name="user[address]" type="email" />
|
196
|
-
<input id="user_favorite_color" name="user[favorite_color]" type="color" value="#000000" />
|
197
|
-
<input id="task_started_at" name="task[started_at]" type="time" />
|
198
|
-
<input id="product_price" max="20.0" min="1.0" name="product[price]" step="0.5" type="number" />
|
199
|
-
<input id="product_discount" max="100" min="1" name="product[discount]" type="range" />
|
200
|
-
```
|
201
|
-
|
202
|
-
Hidden inputs are not shown to the user but instead hold data like any textual input. Values inside them can be changed with JavaScript.
|
203
|
-
|
204
|
-
IMPORTANT: The search, telephone, date, time, color, datetime, datetime-local,
|
205
|
-
month, week, URL, email, number and range inputs are HTML5 controls.
|
206
|
-
If you require your app to have a consistent experience in older browsers,
|
207
|
-
you will need an HTML5 polyfill (provided by CSS and/or JavaScript).
|
208
|
-
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
|
209
|
-
[Modernizr](http://www.modernizr.com/) and [yepnope](http://yepnopejs.com/),
|
210
|
-
which provide a simple way to add functionality based on the presence of
|
211
|
-
detected HTML5 features.
|
212
|
-
|
213
|
-
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).
|
214
|
-
|
215
|
-
Dealing with Model Objects
|
216
|
-
--------------------------
|
217
|
-
|
218
|
-
### Model Object Helpers
|
219
|
-
|
220
|
-
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`.
|
221
|
-
|
222
|
-
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:
|
223
|
-
|
224
|
-
```erb
|
225
|
-
<%= text_field(:person, :name) %>
|
226
|
-
```
|
227
|
-
|
228
|
-
will produce output similar to
|
229
|
-
|
230
|
-
```erb
|
231
|
-
<input id="person_name" name="person[name]" type="text" value="Henry"/>
|
232
|
-
```
|
233
|
-
|
234
|
-
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.
|
235
|
-
|
236
|
-
WARNING: You must pass the name of an instance variable, i.e. `:person` or `"person"`, not an actual instance of your model object.
|
237
|
-
|
238
|
-
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.
|
239
|
-
|
240
|
-
### Binding a Form to an Object
|
241
|
-
|
242
|
-
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.
|
243
|
-
|
244
|
-
Assume we have a controller for dealing with articles `app/controllers/articles_controller.rb`:
|
245
|
-
|
246
|
-
```ruby
|
247
|
-
def new
|
248
|
-
@article = Article.new
|
249
|
-
end
|
250
|
-
```
|
251
|
-
|
252
|
-
The corresponding view `app/views/articles/new.html.erb` using `form_for` looks like this:
|
253
|
-
|
254
|
-
```erb
|
255
|
-
<%= form_for @article, url: {action: "create"}, html: {class: "nifty_form"} do |f| %>
|
256
|
-
<%= f.text_field :title %>
|
257
|
-
<%= f.text_area :body, size: "60x12" %>
|
258
|
-
<%= f.submit "Create" %>
|
259
|
-
<% end %>
|
260
|
-
```
|
261
|
-
|
262
|
-
There are a few things to note here:
|
263
|
-
|
264
|
-
* `@article` is the actual object being edited.
|
265
|
-
* 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.
|
266
|
-
* The `form_for` method yields a **form builder** object (the `f` variable).
|
267
|
-
* Methods to create form controls are called **on** the form builder object `f`
|
268
|
-
|
269
|
-
The resulting HTML is:
|
270
|
-
|
271
|
-
```html
|
272
|
-
<form accept-charset="UTF-8" action="/articles/create" method="post" class="nifty_form">
|
273
|
-
<input id="article_title" name="article[title]" type="text" />
|
274
|
-
<textarea id="article_body" name="article[body]" cols="60" rows="12"></textarea>
|
275
|
-
<input name="commit" type="submit" value="Create" />
|
276
|
-
</form>
|
277
|
-
```
|
278
|
-
|
279
|
-
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.
|
280
|
-
|
281
|
-
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.
|
282
|
-
|
283
|
-
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:
|
284
|
-
|
285
|
-
```erb
|
286
|
-
<%= form_for @person, url: {action: "create"} do |person_form| %>
|
287
|
-
<%= person_form.text_field :name %>
|
288
|
-
<%= fields_for @person.contact_detail do |contact_details_form| %>
|
289
|
-
<%= contact_details_form.text_field :phone_number %>
|
290
|
-
<% end %>
|
291
|
-
<% end %>
|
292
|
-
```
|
293
|
-
|
294
|
-
which produces the following output:
|
295
|
-
|
296
|
-
```html
|
297
|
-
<form accept-charset="UTF-8" action="/people/create" class="new_person" id="new_person" method="post">
|
298
|
-
<input id="person_name" name="person[name]" type="text" />
|
299
|
-
<input id="contact_detail_phone_number" name="contact_detail[phone_number]" type="text" />
|
300
|
-
</form>
|
301
|
-
```
|
302
|
-
|
303
|
-
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).
|
304
|
-
|
305
|
-
### Relying on Record Identification
|
306
|
-
|
307
|
-
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**:
|
308
|
-
|
309
|
-
```ruby
|
310
|
-
resources :articles
|
311
|
-
```
|
312
|
-
|
313
|
-
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.
|
314
|
-
|
315
|
-
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:
|
316
|
-
|
317
|
-
```ruby
|
318
|
-
## Creating a new article
|
319
|
-
# long-style:
|
320
|
-
form_for(@article, url: articles_path)
|
321
|
-
# same thing, short-style (record identification gets used):
|
322
|
-
form_for(@article)
|
323
|
-
|
324
|
-
## Editing an existing article
|
325
|
-
# long-style:
|
326
|
-
form_for(@article, url: article_path(@article), html: {method: "patch"})
|
327
|
-
# short-style:
|
328
|
-
form_for(@article)
|
329
|
-
```
|
330
|
-
|
331
|
-
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.
|
332
|
-
|
333
|
-
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.
|
334
|
-
|
335
|
-
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.
|
336
|
-
|
337
|
-
#### Dealing with Namespaces
|
338
|
-
|
339
|
-
If you have created namespaced routes, `form_for` has a nifty shorthand for that too. If your application has an admin namespace then
|
340
|
-
|
341
|
-
```ruby
|
342
|
-
form_for [:admin, @article]
|
343
|
-
```
|
344
|
-
|
345
|
-
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:
|
346
|
-
|
347
|
-
```ruby
|
348
|
-
form_for [:admin, :management, @article]
|
349
|
-
```
|
350
|
-
|
351
|
-
For more information on Rails' routing system and the associated conventions, please see the [routing guide](routing.html).
|
352
|
-
|
353
|
-
|
354
|
-
### How do forms with PATCH, PUT, or DELETE methods work?
|
355
|
-
|
356
|
-
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.
|
357
|
-
|
358
|
-
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:
|
359
|
-
|
360
|
-
```ruby
|
361
|
-
form_tag(search_path, method: "patch")
|
362
|
-
```
|
363
|
-
|
364
|
-
output:
|
365
|
-
|
366
|
-
```html
|
367
|
-
<form accept-charset="UTF-8" action="/search" method="post">
|
368
|
-
<div style="margin:0;padding:0">
|
369
|
-
<input name="_method" type="hidden" value="patch" />
|
370
|
-
<input name="utf8" type="hidden" value="✓" />
|
371
|
-
<input name="authenticity_token" type="hidden" value="f755bb0ed134b76c432144748a6d4b7a7ddf2b71" />
|
372
|
-
</div>
|
373
|
-
...
|
374
|
-
```
|
375
|
-
|
376
|
-
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).
|
377
|
-
|
378
|
-
Making Select Boxes with Ease
|
379
|
-
-----------------------------
|
380
|
-
|
381
|
-
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.
|
382
|
-
|
383
|
-
Here is what the markup might look like:
|
384
|
-
|
385
|
-
```html
|
386
|
-
<select name="city_id" id="city_id">
|
387
|
-
<option value="1">Lisbon</option>
|
388
|
-
<option value="2">Madrid</option>
|
389
|
-
...
|
390
|
-
<option value="12">Berlin</option>
|
391
|
-
</select>
|
392
|
-
```
|
393
|
-
|
394
|
-
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.
|
395
|
-
|
396
|
-
### The Select and Option Tags
|
397
|
-
|
398
|
-
The most generic helper is `select_tag`, which - as the name implies - simply generates the `SELECT` tag that encapsulates an options string:
|
399
|
-
|
400
|
-
```erb
|
401
|
-
<%= select_tag(:city_id, '<option value="1">Lisbon</option>...') %>
|
402
|
-
```
|
403
|
-
|
404
|
-
This is a start, but it doesn't dynamically create the option tags. You can generate option tags with the `options_for_select` helper:
|
405
|
-
|
406
|
-
```html+erb
|
407
|
-
<%= options_for_select([['Lisbon', 1], ['Madrid', 2], ...]) %>
|
408
|
-
|
409
|
-
output:
|
410
|
-
|
411
|
-
<option value="1">Lisbon</option>
|
412
|
-
<option value="2">Madrid</option>
|
413
|
-
...
|
414
|
-
```
|
415
|
-
|
416
|
-
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.
|
417
|
-
|
418
|
-
Knowing this, you can combine `select_tag` and `options_for_select` to achieve the desired, complete markup:
|
419
|
-
|
420
|
-
```erb
|
421
|
-
<%= select_tag(:city_id, options_for_select(...)) %>
|
422
|
-
```
|
423
|
-
|
424
|
-
`options_for_select` allows you to pre-select an option by passing its value.
|
425
|
-
|
426
|
-
```html+erb
|
427
|
-
<%= options_for_select([['Lisbon', 1], ['Madrid', 2], ...], 2) %>
|
428
|
-
|
429
|
-
output:
|
430
|
-
|
431
|
-
<option value="1">Lisbon</option>
|
432
|
-
<option value="2" selected="selected">Madrid</option>
|
433
|
-
...
|
434
|
-
```
|
435
|
-
|
436
|
-
Whenever Rails sees that the internal value of an option being generated matches this value, it will add the `selected` attribute to that option.
|
437
|
-
|
438
|
-
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.
|
439
|
-
|
440
|
-
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.
|
441
|
-
|
442
|
-
You can add arbitrary attributes to the options using hashes:
|
443
|
-
|
444
|
-
```html+erb
|
445
|
-
<%= options_for_select([['Lisbon', 1, {'data-size' => '2.8 million'}], ['Madrid', 2, {'data-size' => '3.2 million'}]], 2) %>
|
446
|
-
|
447
|
-
output:
|
448
|
-
|
449
|
-
<option value="1" data-size="2.8 million">Lisbon</option>
|
450
|
-
<option value="2" selected="selected" data-size="3.2 million">Madrid</option>
|
451
|
-
...
|
452
|
-
```
|
453
|
-
|
454
|
-
### Select Boxes for Dealing with Models
|
455
|
-
|
456
|
-
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`:
|
457
|
-
|
458
|
-
```ruby
|
459
|
-
# controller:
|
460
|
-
@person = Person.new(city_id: 2)
|
461
|
-
```
|
462
|
-
|
463
|
-
```erb
|
464
|
-
# view:
|
465
|
-
<%= select(:person, :city_id, [['Lisbon', 1], ['Madrid', 2], ...]) %>
|
466
|
-
```
|
467
|
-
|
468
|
-
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.
|
469
|
-
|
470
|
-
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:
|
471
|
-
|
472
|
-
```erb
|
473
|
-
# select on a form builder
|
474
|
-
<%= f.select(:city_id, ...) %>
|
475
|
-
```
|
476
|
-
|
477
|
-
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.
|
478
|
-
|
479
|
-
### Option Tags from a Collection of Arbitrary Objects
|
480
|
-
|
481
|
-
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:
|
482
|
-
|
483
|
-
```erb
|
484
|
-
<% cities_array = City.all.map { |city| [city.name, city.id] } %>
|
485
|
-
<%= options_for_select(cities_array) %>
|
486
|
-
```
|
487
|
-
|
488
|
-
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:
|
489
|
-
|
490
|
-
```erb
|
491
|
-
<%= options_from_collection_for_select(City.all, :id, :name) %>
|
492
|
-
```
|
493
|
-
|
494
|
-
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`.
|
495
|
-
|
496
|
-
```erb
|
497
|
-
<%= collection_select(:person, :city_id, City.all, :id, :name) %>
|
498
|
-
```
|
499
|
-
|
500
|
-
To recap, `options_from_collection_for_select` is to `collection_select` what `options_for_select` is to `select`.
|
501
|
-
|
502
|
-
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.
|
503
|
-
|
504
|
-
### Time Zone and Country Select
|
505
|
-
|
506
|
-
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:
|
507
|
-
|
508
|
-
```erb
|
509
|
-
<%= time_zone_select(:person, :time_zone) %>
|
510
|
-
```
|
511
|
-
|
512
|
-
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.
|
513
|
-
|
514
|
-
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).
|
515
|
-
|
516
|
-
Using Date and Time Form Helpers
|
517
|
-
--------------------------------
|
518
|
-
|
519
|
-
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:
|
520
|
-
|
521
|
-
* 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.
|
522
|
-
* 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.
|
523
|
-
|
524
|
-
Both of these families of helpers will create a series of select boxes for the different components (year, month, day etc.).
|
525
|
-
|
526
|
-
### Barebones Helpers
|
527
|
-
|
528
|
-
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
|
529
|
-
|
530
|
-
```erb
|
531
|
-
<%= select_date Date.today, prefix: :start_date %>
|
532
|
-
```
|
533
|
-
|
534
|
-
outputs (with actual option values omitted for brevity)
|
535
|
-
|
536
|
-
```html
|
537
|
-
<select id="start_date_year" name="start_date[year]"> ... </select>
|
538
|
-
<select id="start_date_month" name="start_date[month]"> ... </select>
|
539
|
-
<select id="start_date_day" name="start_date[day]"> ... </select>
|
540
|
-
```
|
541
|
-
|
542
|
-
The above inputs would result in `params[:start_date]` being a hash with keys `:year`, `:month`, `:day`. To get an actual Time or Date object you would have to extract these values and pass them to the appropriate constructor, for example
|
543
|
-
|
544
|
-
```ruby
|
545
|
-
Date.civil(params[:start_date][:year].to_i, params[:start_date][:month].to_i, params[:start_date][:day].to_i)
|
546
|
-
```
|
547
|
-
|
548
|
-
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`.
|
549
|
-
|
550
|
-
### Model Object Helpers
|
551
|
-
|
552
|
-
`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.
|
553
|
-
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:
|
554
|
-
|
555
|
-
```erb
|
556
|
-
<%= date_select :person, :birth_date %>
|
557
|
-
```
|
558
|
-
|
559
|
-
outputs (with actual option values omitted for brevity)
|
560
|
-
|
561
|
-
```html
|
562
|
-
<select id="person_birth_date_1i" name="person[birth_date(1i)]"> ... </select>
|
563
|
-
<select id="person_birth_date_2i" name="person[birth_date(2i)]"> ... </select>
|
564
|
-
<select id="person_birth_date_3i" name="person[birth_date(3i)]"> ... </select>
|
565
|
-
```
|
566
|
-
|
567
|
-
which results in a `params` hash like
|
568
|
-
|
569
|
-
```ruby
|
570
|
-
{'person' => {'birth_date(1i)' => '2008', 'birth_date(2i)' => '11', 'birth_date(3i)' => '22'}}
|
571
|
-
```
|
572
|
-
|
573
|
-
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`.
|
574
|
-
|
575
|
-
### Common Options
|
576
|
-
|
577
|
-
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).
|
578
|
-
|
579
|
-
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.
|
580
|
-
|
581
|
-
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.
|
582
|
-
|
583
|
-
### Individual Components
|
584
|
-
|
585
|
-
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.
|
586
|
-
|
587
|
-
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
|
588
|
-
|
589
|
-
```erb
|
590
|
-
<%= select_year(2009) %>
|
591
|
-
<%= select_year(Time.now) %>
|
592
|
-
```
|
593
|
-
|
594
|
-
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]`.
|
595
|
-
|
596
|
-
Uploading Files
|
597
|
-
---------------
|
598
|
-
|
599
|
-
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.
|
600
|
-
|
601
|
-
The following two forms both upload a file.
|
602
|
-
|
603
|
-
```erb
|
604
|
-
<%= form_tag({action: :upload}, multipart: true) do %>
|
605
|
-
<%= file_field_tag 'picture' %>
|
606
|
-
<% end %>
|
607
|
-
|
608
|
-
<%= form_for @person do |f| %>
|
609
|
-
<%= f.file_field :picture %>
|
610
|
-
<% end %>
|
611
|
-
```
|
612
|
-
|
613
|
-
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]`.
|
614
|
-
|
615
|
-
### What Gets Uploaded
|
616
|
-
|
617
|
-
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).
|
618
|
-
|
619
|
-
```ruby
|
620
|
-
def upload
|
621
|
-
uploaded_io = params[:person][:picture]
|
622
|
-
File.open(Rails.root.join('public', 'uploads', uploaded_io.original_filename), 'wb') do |file|
|
623
|
-
file.write(uploaded_io.read)
|
624
|
-
end
|
625
|
-
end
|
626
|
-
```
|
627
|
-
|
628
|
-
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](http://www.thoughtbot.com/projects/paperclip).
|
629
|
-
|
630
|
-
NOTE: If the user has not selected a file the corresponding parameter will be an empty string.
|
631
|
-
|
632
|
-
### Dealing with Ajax
|
633
|
-
|
634
|
-
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.
|
635
|
-
|
636
|
-
Customizing Form Builders
|
637
|
-
-------------------------
|
638
|
-
|
639
|
-
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
|
640
|
-
|
641
|
-
```erb
|
642
|
-
<%= form_for @person do |f| %>
|
643
|
-
<%= text_field_with_label f, :first_name %>
|
644
|
-
<% end %>
|
645
|
-
```
|
646
|
-
|
647
|
-
can be replaced with
|
648
|
-
|
649
|
-
```erb
|
650
|
-
<%= form_for @person, builder: LabellingFormBuilder do |f| %>
|
651
|
-
<%= f.text_field :first_name %>
|
652
|
-
<% end %>
|
653
|
-
```
|
654
|
-
|
655
|
-
by defining a LabellingFormBuilder class similar to the following:
|
656
|
-
|
657
|
-
```ruby
|
658
|
-
class LabellingFormBuilder < ActionView::Helpers::FormBuilder
|
659
|
-
def text_field(attribute, options={})
|
660
|
-
label(attribute) + super
|
661
|
-
end
|
662
|
-
end
|
663
|
-
```
|
664
|
-
|
665
|
-
If you reuse this frequently you could define a `labeled_form_for` helper that automatically applies the `builder: LabellingFormBuilder` option.
|
666
|
-
|
667
|
-
The form builder used also determines what happens when you do
|
668
|
-
|
669
|
-
```erb
|
670
|
-
<%= render partial: f %>
|
671
|
-
```
|
672
|
-
|
673
|
-
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.
|
674
|
-
|
675
|
-
Understanding Parameter Naming Conventions
|
676
|
-
------------------------------------------
|
677
|
-
|
678
|
-
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`
|
679
|
-
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.
|
680
|
-
|
681
|
-
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.
|
682
|
-
|
683
|
-
TIP: You may find you can try out examples in this section faster by using the console to directly invoke Racks' parameter parser. For example,
|
684
|
-
|
685
|
-
```ruby
|
686
|
-
Rack::Utils.parse_query "name=fred&phone=0123456789"
|
687
|
-
# => {"name"=>"fred", "phone"=>"0123456789"}
|
688
|
-
```
|
689
|
-
|
690
|
-
### Basic Structures
|
691
|
-
|
692
|
-
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
|
693
|
-
|
694
|
-
```html
|
695
|
-
<input id="person_name" name="person[name]" type="text" value="Henry"/>
|
696
|
-
```
|
697
|
-
|
698
|
-
the `params` hash will contain
|
699
|
-
|
700
|
-
```erb
|
701
|
-
{'person' => {'name' => 'Henry'}}
|
702
|
-
```
|
703
|
-
|
704
|
-
and `params[:person][:name]` will retrieve the submitted value in the controller.
|
705
|
-
|
706
|
-
Hashes can be nested as many levels as required, for example
|
707
|
-
|
708
|
-
```html
|
709
|
-
<input id="person_address_city" name="person[address][city]" type="text" value="New York"/>
|
710
|
-
```
|
711
|
-
|
712
|
-
will result in the `params` hash being
|
713
|
-
|
714
|
-
```ruby
|
715
|
-
{'person' => {'address' => {'city' => 'New York'}}}
|
716
|
-
```
|
717
|
-
|
718
|
-
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:
|
719
|
-
|
720
|
-
```html
|
721
|
-
<input name="person[phone_number][]" type="text"/>
|
722
|
-
<input name="person[phone_number][]" type="text"/>
|
723
|
-
<input name="person[phone_number][]" type="text"/>
|
724
|
-
```
|
725
|
-
|
726
|
-
This would result in `params[:person][:phone_number]` being an array.
|
727
|
-
|
728
|
-
### Combining Them
|
729
|
-
|
730
|
-
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
|
731
|
-
|
732
|
-
```html
|
733
|
-
<input name="addresses[][line1]" type="text"/>
|
734
|
-
<input name="addresses[][line2]" type="text"/>
|
735
|
-
<input name="addresses[][city]" type="text"/>
|
736
|
-
```
|
737
|
-
|
738
|
-
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.
|
739
|
-
|
740
|
-
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.
|
741
|
-
|
742
|
-
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.
|
743
|
-
|
744
|
-
### Using Form Helpers
|
745
|
-
|
746
|
-
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.
|
747
|
-
|
748
|
-
You might want to render a form with a set of edit fields for each of a person's addresses. For example:
|
749
|
-
|
750
|
-
```erb
|
751
|
-
<%= form_for @person do |person_form| %>
|
752
|
-
<%= person_form.text_field :name %>
|
753
|
-
<% @person.addresses.each do |address| %>
|
754
|
-
<%= person_form.fields_for address, index: address.id do |address_form|%>
|
755
|
-
<%= address_form.text_field :city %>
|
756
|
-
<% end %>
|
757
|
-
<% end %>
|
758
|
-
<% end %>
|
759
|
-
```
|
760
|
-
|
761
|
-
Assuming the person had two addresses, with ids 23 and 45 this would create output similar to this:
|
762
|
-
|
763
|
-
```html
|
764
|
-
<form accept-charset="UTF-8" action="/people/1" class="edit_person" id="edit_person_1" method="post">
|
765
|
-
<input id="person_name" name="person[name]" type="text" />
|
766
|
-
<input id="person_address_23_city" name="person[address][23][city]" type="text" />
|
767
|
-
<input id="person_address_45_city" name="person[address][45][city]" type="text" />
|
768
|
-
</form>
|
769
|
-
```
|
770
|
-
|
771
|
-
This will result in a `params` hash that looks like
|
772
|
-
|
773
|
-
```ruby
|
774
|
-
{'person' => {'name' => 'Bob', 'address' => {'23' => {'city' => 'Paris'}, '45' => {'city' => 'London'}}}}
|
775
|
-
```
|
776
|
-
|
777
|
-
Rails knows that all these inputs should be part of the person hash because you
|
778
|
-
called `fields_for` on the first form builder. By specifying an `:index` option
|
779
|
-
you're telling Rails that instead of naming the inputs `person[address][city]`
|
780
|
-
it should insert that index surrounded by [] between the address and the city.
|
781
|
-
This is often useful as it is then easy to locate which Address record
|
782
|
-
should be modified. You can pass numbers with some other significance,
|
783
|
-
strings or even `nil` (which will result in an array parameter being created).
|
784
|
-
|
785
|
-
To create more intricate nestings, you can specify the first part of the input
|
786
|
-
name (`person[address]` in the previous example) explicitly:
|
787
|
-
|
788
|
-
```erb
|
789
|
-
<%= fields_for 'person[address][primary]', address, index: address do |address_form| %>
|
790
|
-
<%= address_form.text_field :city %>
|
791
|
-
<% end %>
|
792
|
-
```
|
793
|
-
|
794
|
-
will create inputs like
|
795
|
-
|
796
|
-
```html
|
797
|
-
<input id="person_address_primary_1_city" name="person[address][primary][1][city]" type="text" value="bologna" />
|
798
|
-
```
|
799
|
-
|
800
|
-
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.
|
801
|
-
|
802
|
-
As a shortcut you can append [] to the name and omit the `:index` option. This is the same as specifying `index: address` so
|
803
|
-
|
804
|
-
```erb
|
805
|
-
<%= fields_for 'person[address][primary][]', address do |address_form| %>
|
806
|
-
<%= address_form.text_field :city %>
|
807
|
-
<% end %>
|
808
|
-
```
|
809
|
-
|
810
|
-
produces exactly the same output as the previous example.
|
811
|
-
|
812
|
-
Forms to external resources
|
813
|
-
---------------------------
|
814
|
-
|
815
|
-
If you need to post some data to an external resource it is still great to build your form using rails form helpers. But sometimes you need to set an `authenticity_token` for this resource. You can do it by passing an `authenticity_token: 'your_external_token'` parameter to the `form_tag` options:
|
816
|
-
|
817
|
-
```erb
|
818
|
-
<%= form_tag 'http://farfar.away/form', authenticity_token: 'external_token') do %>
|
819
|
-
Form contents
|
820
|
-
<% end %>
|
821
|
-
```
|
822
|
-
|
823
|
-
Sometimes when you submit data to an external resource, like payment gateway, fields you can use in your form are limited by an external API. So you may want not to generate an `authenticity_token` hidden field at all. For doing this just pass `false` to the `:authenticity_token` option:
|
824
|
-
|
825
|
-
```erb
|
826
|
-
<%= form_tag 'http://farfar.away/form', authenticity_token: false) do %>
|
827
|
-
Form contents
|
828
|
-
<% end %>
|
829
|
-
```
|
830
|
-
|
831
|
-
The same technique is also available for `form_for`:
|
832
|
-
|
833
|
-
```erb
|
834
|
-
<%= form_for @invoice, url: external_url, authenticity_token: 'external_token' do |f| %>
|
835
|
-
Form contents
|
836
|
-
<% end %>
|
837
|
-
```
|
838
|
-
|
839
|
-
Or if you don't want to render an `authenticity_token` field:
|
840
|
-
|
841
|
-
```erb
|
842
|
-
<%= form_for @invoice, url: external_url, authenticity_token: false do |f| %>
|
843
|
-
Form contents
|
844
|
-
<% end %>
|
845
|
-
```
|
846
|
-
|
847
|
-
Building Complex Forms
|
848
|
-
----------------------
|
849
|
-
|
850
|
-
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.
|
851
|
-
|
852
|
-
### Configuring the Model
|
853
|
-
|
854
|
-
Active Record provides model level support via the `accepts_nested_attributes_for` method:
|
855
|
-
|
856
|
-
```ruby
|
857
|
-
class Person < ActiveRecord::Base
|
858
|
-
has_many :addresses
|
859
|
-
accepts_nested_attributes_for :addresses
|
860
|
-
end
|
861
|
-
|
862
|
-
class Address < ActiveRecord::Base
|
863
|
-
belongs_to :person
|
864
|
-
end
|
865
|
-
```
|
866
|
-
|
867
|
-
This creates an `addresses_attributes=` method on `Person` that allows you to create, update and (optionally) destroy addresses.
|
868
|
-
|
869
|
-
### Nested Forms
|
870
|
-
|
871
|
-
The following form allows a user to create a `Person` and its associated addresses.
|
872
|
-
|
873
|
-
```html+erb
|
874
|
-
<%= form_for @person do |f| %>
|
875
|
-
Addresses:
|
876
|
-
<ul>
|
877
|
-
<%= f.fields_for :addresses do |addresses_form| %>
|
878
|
-
<li>
|
879
|
-
<%= addresses_form.label :kind %>
|
880
|
-
<%= addresses_form.text_field :kind %>
|
881
|
-
|
882
|
-
<%= addresses_form.label :street %>
|
883
|
-
<%= addresses_form.text_field :street %>
|
884
|
-
...
|
885
|
-
</li>
|
886
|
-
<% end %>
|
887
|
-
</ul>
|
888
|
-
<% end %>
|
889
|
-
```
|
890
|
-
|
891
|
-
|
892
|
-
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.
|
893
|
-
|
894
|
-
```ruby
|
895
|
-
def new
|
896
|
-
@person = Person.new
|
897
|
-
2.times { @person.addresses.build}
|
898
|
-
end
|
899
|
-
```
|
900
|
-
|
901
|
-
The `fields_for` yields a form builder. The parameters' name will be what
|
902
|
-
`accepts_nested_attributes_for` expects. For example when creating a user with
|
903
|
-
2 addresses, the submitted parameters would look like:
|
904
|
-
|
905
|
-
```ruby
|
906
|
-
{
|
907
|
-
'person' => {
|
908
|
-
'name' => 'John Doe',
|
909
|
-
'addresses_attributes' => {
|
910
|
-
'0' => {
|
911
|
-
'kind' => 'Home',
|
912
|
-
'street' => '221b Baker Street'
|
913
|
-
},
|
914
|
-
'1' => {
|
915
|
-
'kind' => 'Office',
|
916
|
-
'street' => '31 Spooner Street'
|
917
|
-
}
|
918
|
-
}
|
919
|
-
}
|
920
|
-
}
|
921
|
-
```
|
922
|
-
|
923
|
-
The keys of the `:addresses_attributes` hash are unimportant, they need merely be different for each address.
|
924
|
-
|
925
|
-
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`.
|
926
|
-
|
927
|
-
### The Controller
|
928
|
-
|
929
|
-
As usual you need to
|
930
|
-
[whitelist the parameters](action_controller_overview.html#strong-parameters) in
|
931
|
-
the controller before you pass them to the model:
|
932
|
-
|
933
|
-
```ruby
|
934
|
-
def create
|
935
|
-
@person = Person.new(person_params)
|
936
|
-
# ...
|
937
|
-
end
|
938
|
-
|
939
|
-
private
|
940
|
-
def person_params
|
941
|
-
params.require(:person).permit(:name, addresses_attributes: [:id, :kind, :street])
|
942
|
-
end
|
943
|
-
```
|
944
|
-
|
945
|
-
### Removing Objects
|
946
|
-
|
947
|
-
You can allow users to delete associated objects by passing `allow_destroy: true` to `accepts_nested_attributes_for`
|
948
|
-
|
949
|
-
```ruby
|
950
|
-
class Person < ActiveRecord::Base
|
951
|
-
has_many :addresses
|
952
|
-
accepts_nested_attributes_for :addresses, allow_destroy: true
|
953
|
-
end
|
954
|
-
```
|
955
|
-
|
956
|
-
If the hash of attributes for an object contains the key `_destroy` with a value
|
957
|
-
of `1` or `true` then the object will be destroyed. This form allows users to
|
958
|
-
remove addresses:
|
959
|
-
|
960
|
-
```erb
|
961
|
-
<%= form_for @person do |f| %>
|
962
|
-
Addresses:
|
963
|
-
<ul>
|
964
|
-
<%= f.fields_for :addresses do |addresses_form| %>
|
965
|
-
<li>
|
966
|
-
<%= addresses_form.check_box :_destroy%>
|
967
|
-
<%= addresses_form.label :kind %>
|
968
|
-
<%= addresses_form.text_field :kind %>
|
969
|
-
...
|
970
|
-
</li>
|
971
|
-
<% end %>
|
972
|
-
</ul>
|
973
|
-
<% end %>
|
974
|
-
```
|
975
|
-
|
976
|
-
Don't forget to update the whitelisted params in your controller to also include
|
977
|
-
the `_destroy` field:
|
978
|
-
|
979
|
-
```ruby
|
980
|
-
def person_params
|
981
|
-
params.require(:person).
|
982
|
-
permit(:name, addresses_attributes: [:id, :kind, :street, :_destroy])
|
983
|
-
end
|
984
|
-
```
|
985
|
-
|
986
|
-
### Preventing Empty Records
|
987
|
-
|
988
|
-
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.
|
989
|
-
|
990
|
-
```ruby
|
991
|
-
class Person < ActiveRecord::Base
|
992
|
-
has_many :addresses
|
993
|
-
accepts_nested_attributes_for :addresses, reject_if: lambda {|attributes| attributes['kind'].blank?}
|
994
|
-
end
|
995
|
-
```
|
996
|
-
|
997
|
-
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`.
|
998
|
-
|
999
|
-
### Adding Fields on the Fly
|
1000
|
-
|
1001
|
-
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 builtin 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.
|