rails 4.0.0 → 4.2.11.3
Sign up to get free protection for your applications and to get access to all the features.
- checksums.yaml +5 -5
- data/README.md +30 -23
- data/guides/CHANGELOG.md +108 -6
- data/guides/Rakefile +21 -6
- data/guides/assets/images/akshaysurve.jpg +0 -0
- data/guides/assets/images/edge_badge.png +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/header_tile.gif +0 -0
- data/guides/assets/images/icons/README +1 -1
- 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/15.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/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/vijaydev.jpg +0 -0
- data/guides/assets/javascripts/guides.js +36 -34
- data/guides/assets/stylesheets/main.css +6 -2
- data/guides/assets/stylesheets/print.css +1 -1
- data/guides/bug_report_templates/action_controller_gem.rb +47 -0
- data/guides/bug_report_templates/action_controller_master.rb +54 -0
- data/guides/bug_report_templates/active_record_gem.rb +5 -2
- data/guides/bug_report_templates/active_record_master.rb +3 -2
- data/guides/bug_report_templates/generic_gem.rb +15 -0
- data/guides/bug_report_templates/generic_master.rb +26 -0
- data/guides/rails_guides.rb +23 -4
- data/guides/rails_guides/generator.rb +1 -1
- data/guides/rails_guides/helpers.rb +4 -2
- data/guides/rails_guides/levenshtein.rb +27 -21
- data/guides/rails_guides/markdown.rb +11 -7
- data/guides/rails_guides/markdown/renderer.rb +1 -1
- data/guides/source/2_2_release_notes.md +3 -3
- data/guides/source/2_3_release_notes.md +12 -12
- data/guides/source/3_0_release_notes.md +10 -13
- data/guides/source/3_1_release_notes.md +7 -4
- data/guides/source/3_2_release_notes.md +17 -14
- data/guides/source/4_0_release_notes.md +110 -54
- data/guides/source/4_1_release_notes.md +730 -0
- data/guides/source/4_2_release_notes.md +877 -0
- data/guides/source/_license.html.erb +1 -1
- data/guides/source/_welcome.html.erb +6 -2
- data/guides/source/action_controller_overview.md +223 -57
- data/guides/source/action_mailer_basics.md +129 -76
- data/guides/source/action_view_overview.md +247 -246
- data/guides/source/active_job_basics.md +339 -0
- data/guides/source/active_model_basics.md +374 -20
- data/guides/source/active_record_basics.md +46 -45
- data/guides/source/active_record_callbacks.md +83 -28
- data/guides/source/{migrations.md → active_record_migrations.md} +191 -275
- data/guides/source/active_record_postgresql.md +433 -0
- data/guides/source/active_record_querying.md +382 -300
- data/guides/source/active_record_validations.md +64 -55
- data/guides/source/active_support_core_extensions.md +229 -187
- data/guides/source/active_support_instrumentation.md +23 -22
- data/guides/source/api_documentation_guidelines.md +167 -15
- data/guides/source/asset_pipeline.md +768 -294
- data/guides/source/association_basics.md +188 -96
- data/guides/source/autoloading_and_reloading_constants.md +1311 -0
- data/guides/source/caching_with_rails.md +45 -11
- data/guides/source/command_line.md +96 -65
- data/guides/source/configuring.md +404 -70
- data/guides/source/contributing_to_ruby_on_rails.md +270 -130
- data/guides/source/credits.html.erb +7 -3
- data/guides/source/debugging_rails_applications.md +471 -284
- data/guides/source/development_dependencies_install.md +115 -21
- data/guides/source/documents.yaml +31 -9
- data/guides/source/engines.md +737 -291
- data/guides/source/form_helpers.md +137 -89
- data/guides/source/generators.md +60 -28
- data/guides/source/getting_started.md +1007 -596
- data/guides/source/i18n.md +178 -96
- data/guides/source/index.html.erb +2 -1
- data/guides/source/initialization.md +248 -104
- data/guides/source/kindle/toc.html.erb +1 -1
- data/guides/source/layout.html.erb +14 -22
- data/guides/source/layouts_and_rendering.md +78 -46
- data/guides/source/maintenance_policy.md +78 -0
- data/guides/source/nested_model_forms.md +10 -7
- data/guides/source/plugins.md +66 -57
- data/guides/source/rails_application_templates.md +49 -12
- data/guides/source/rails_on_rack.md +50 -60
- data/guides/source/routing.md +190 -139
- data/guides/source/ruby_on_rails_guides_guidelines.md +12 -13
- data/guides/source/security.md +134 -83
- data/guides/source/testing.md +322 -200
- data/guides/source/upgrading_ruby_on_rails.md +834 -37
- data/guides/source/working_with_javascript_in_rails.md +36 -26
- data/guides/w3c_validator.rb +2 -0
- metadata +93 -116
- data/guides/assets/images/getting_started/forbidden_attributes_for_new_post.png +0 -0
- data/guides/assets/images/getting_started/new_post.png +0 -0
- data/guides/assets/images/getting_started/post_with_comments.png +0 -0
- data/guides/assets/images/getting_started/show_action_for_posts.png +0 -0
- data/guides/assets/images/getting_started/template_is_missing_posts_new.png +0 -0
- data/guides/assets/images/getting_started/undefined_method_post_path.png +0 -0
- data/guides/assets/images/getting_started/unknown_action_create_for_posts.png +0 -0
- data/guides/assets/images/getting_started/unknown_action_new_for_posts.png +0 -0
- data/guides/assets/images/jaimeiniesta.jpg +0 -0
- data/guides/code/getting_started/Gemfile +0 -43
- data/guides/code/getting_started/Gemfile.lock +0 -150
- 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 -16
- 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 -17
- data/guides/code/getting_started/app/controllers/posts_controller.rb +0 -47
- 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 -3
- 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 -58
- data/guides/code/getting_started/public/422.html +0 -58
- data/guides/code/getting_started/public/500.html +0 -57
- 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 -15
- data/guides/source/kindle/KINDLE.md +0 -26
@@ -1,23 +1,22 @@
|
|
1
1
|
Form Helpers
|
2
2
|
============
|
3
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
|
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
5
|
|
6
6
|
After reading this guide, you will know:
|
7
7
|
|
8
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
|
9
|
+
* How to make model-centric forms for creating and editing specific database records.
|
10
10
|
* How to generate select boxes from multiple types of data.
|
11
|
-
*
|
11
|
+
* What date and time helpers Rails provides.
|
12
12
|
* What makes a file upload form different.
|
13
|
-
*
|
13
|
+
* How to post forms to external resources and specify setting an `authenticity_token`.
|
14
14
|
* How to build complex forms.
|
15
15
|
|
16
16
|
--------------------------------------------------------------------------------
|
17
17
|
|
18
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
19
|
|
20
|
-
|
21
20
|
Dealing with Basic Forms
|
22
21
|
------------------------
|
23
22
|
|
@@ -32,18 +31,14 @@ The most basic form helper is `form_tag`.
|
|
32
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):
|
33
32
|
|
34
33
|
```html
|
35
|
-
<form accept-charset="UTF-8" action="/
|
36
|
-
<
|
37
|
-
|
38
|
-
<input name="authenticity_token" type="hidden" value="f755bb0ed134b76c432144748a6d4b7a7ddf2b71" />
|
39
|
-
</div>
|
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=" />
|
40
37
|
Form contents
|
41
38
|
</form>
|
42
39
|
```
|
43
40
|
|
44
|
-
|
45
|
-
|
46
|
-
NOTE: Throughout this guide, the `div` with the hidden input elements will be excluded from code samples for brevity.
|
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).
|
47
42
|
|
48
43
|
### A Generic Search Form
|
49
44
|
|
@@ -68,13 +63,14 @@ This will generate the following HTML:
|
|
68
63
|
|
69
64
|
```html
|
70
65
|
<form accept-charset="UTF-8" action="/search" method="get">
|
66
|
+
<input name="utf8" type="hidden" value="✓" />
|
71
67
|
<label for="q">Search for:</label>
|
72
68
|
<input id="q" name="q" type="text" />
|
73
69
|
<input name="commit" type="submit" value="Search" />
|
74
70
|
</form>
|
75
71
|
```
|
76
72
|
|
77
|
-
TIP: For every form input, an ID attribute is generated from its name ("q" in
|
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.
|
78
74
|
|
79
75
|
Besides `text_field_tag` and `submit_tag`, there is a similar helper for _every_ form control in HTML.
|
80
76
|
|
@@ -100,7 +96,15 @@ form_tag({controller: "people", action: "search"}, method: "get", class: "nifty_
|
|
100
96
|
|
101
97
|
### Helpers for Generating Form Elements
|
102
98
|
|
103
|
-
Rails provides a series of helpers for generating form elements such as
|
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]`.
|
104
108
|
|
105
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).
|
106
110
|
|
@@ -146,7 +150,7 @@ Output:
|
|
146
150
|
<label for="age_adult">I'm over 21</label>
|
147
151
|
```
|
148
152
|
|
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"
|
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"`.
|
150
154
|
|
151
155
|
NOTE: Always use labels for checkbox and radio buttons. They associate text with a specific option and,
|
152
156
|
by expanding the clickable region,
|
@@ -154,7 +158,10 @@ make it easier for users to click the inputs.
|
|
154
158
|
|
155
159
|
### Other Helpers of Interest
|
156
160
|
|
157
|
-
Other form controls worth mentioning are textareas, password fields,
|
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:
|
158
165
|
|
159
166
|
```erb
|
160
167
|
<%= text_area_tag(:message, "Hi, nice site", size: "24x6") %>
|
@@ -171,6 +178,8 @@ Other form controls worth mentioning are textareas, password fields, hidden fiel
|
|
171
178
|
<%= email_field(:user, :address) %>
|
172
179
|
<%= color_field(:user, :favorite_color) %>
|
173
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) %>
|
174
183
|
```
|
175
184
|
|
176
185
|
Output:
|
@@ -190,11 +199,20 @@ Output:
|
|
190
199
|
<input id="user_address" name="user[address]" type="email" />
|
191
200
|
<input id="user_favorite_color" name="user[favorite_color]" type="color" value="#000000" />
|
192
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" />
|
193
204
|
```
|
194
205
|
|
195
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.
|
196
207
|
|
197
|
-
IMPORTANT: The search, telephone, date, time, color, datetime, datetime-local,
|
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.
|
198
216
|
|
199
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).
|
200
218
|
|
@@ -203,7 +221,7 @@ Dealing with Model Objects
|
|
203
221
|
|
204
222
|
### Model Object Helpers
|
205
223
|
|
206
|
-
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`.
|
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`.
|
207
225
|
|
208
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:
|
209
227
|
|
@@ -225,7 +243,7 @@ Rails provides helpers for displaying the validation errors associated with a mo
|
|
225
243
|
|
226
244
|
### Binding a Form to an Object
|
227
245
|
|
228
|
-
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.
|
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.
|
229
247
|
|
230
248
|
Assume we have a controller for dealing with articles `app/controllers/articles_controller.rb`:
|
231
249
|
|
@@ -250,7 +268,7 @@ There are a few things to note here:
|
|
250
268
|
* `@article` is the actual object being edited.
|
251
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.
|
252
270
|
* The `form_for` method yields a **form builder** object (the `f` variable).
|
253
|
-
* Methods to create form controls are called **on** the form builder object `f
|
271
|
+
* Methods to create form controls are called **on** the form builder object `f`.
|
254
272
|
|
255
273
|
The resulting HTML is:
|
256
274
|
|
@@ -266,7 +284,7 @@ The name passed to `form_for` controls the key used in `params` to access the fo
|
|
266
284
|
|
267
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.
|
268
286
|
|
269
|
-
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:
|
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:
|
270
288
|
|
271
289
|
```erb
|
272
290
|
<%= form_for @person, url: {action: "create"} do |person_form| %>
|
@@ -290,7 +308,7 @@ The object yielded by `fields_for` is a form builder like the one yielded by `fo
|
|
290
308
|
|
291
309
|
### Relying on Record Identification
|
292
310
|
|
293
|
-
The Article model is directly available to users of the application, so
|
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**:
|
294
312
|
|
295
313
|
```ruby
|
296
314
|
resources :articles
|
@@ -328,7 +346,7 @@ If you have created namespaced routes, `form_for` has a nifty shorthand for that
|
|
328
346
|
form_for [:admin, @article]
|
329
347
|
```
|
330
348
|
|
331
|
-
will create a form that submits to the
|
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:
|
332
350
|
|
333
351
|
```ruby
|
334
352
|
form_for [:admin, :management, @article]
|
@@ -336,7 +354,6 @@ form_for [:admin, :management, @article]
|
|
336
354
|
|
337
355
|
For more information on Rails' routing system and the associated conventions, please see the [routing guide](routing.html).
|
338
356
|
|
339
|
-
|
340
357
|
### How do forms with PATCH, PUT, or DELETE methods work?
|
341
358
|
|
342
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.
|
@@ -351,12 +368,11 @@ output:
|
|
351
368
|
|
352
369
|
```html
|
353
370
|
<form accept-charset="UTF-8" action="/search" method="post">
|
354
|
-
<
|
355
|
-
|
356
|
-
|
357
|
-
<input name="authenticity_token" type="hidden" value="f755bb0ed134b76c432144748a6d4b7a7ddf2b71" />
|
358
|
-
</div>
|
371
|
+
<input name="_method" type="hidden" value="patch" />
|
372
|
+
<input name="utf8" type="hidden" value="✓" />
|
373
|
+
<input name="authenticity_token" type="hidden" value="f755bb0ed134b76c432144748a6d4b7a7ddf2b71" />
|
359
374
|
...
|
375
|
+
</form>
|
360
376
|
```
|
361
377
|
|
362
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).
|
@@ -381,7 +397,7 @@ Here you have a list of cities whose names are presented to the user. Internally
|
|
381
397
|
|
382
398
|
### The Select and Option Tags
|
383
399
|
|
384
|
-
The most generic helper is `select_tag`, which
|
400
|
+
The most generic helper is `select_tag`, which - as the name implies - simply generates the `SELECT` tag that encapsulates an options string:
|
385
401
|
|
386
402
|
```erb
|
387
403
|
<%= select_tag(:city_id, '<option value="1">Lisbon</option>...') %>
|
@@ -421,14 +437,19 @@ output:
|
|
421
437
|
|
422
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.
|
423
439
|
|
424
|
-
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`
|
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.
|
425
441
|
|
426
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.
|
427
443
|
|
428
444
|
You can add arbitrary attributes to the options using hashes:
|
429
445
|
|
430
446
|
```html+erb
|
431
|
-
<%= options_for_select(
|
447
|
+
<%= options_for_select(
|
448
|
+
[
|
449
|
+
['Lisbon', 1, { 'data-size' => '2.8 million' }],
|
450
|
+
['Madrid', 2, { 'data-size' => '3.2 million' }]
|
451
|
+
], 2
|
452
|
+
) %>
|
432
453
|
|
433
454
|
output:
|
434
455
|
|
@@ -451,7 +472,7 @@ In most cases form controls will be tied to a specific database model and as you
|
|
451
472
|
<%= select(:person, :city_id, [['Lisbon', 1], ['Madrid', 2], ...]) %>
|
452
473
|
```
|
453
474
|
|
454
|
-
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
|
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.
|
455
476
|
|
456
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:
|
457
478
|
|
@@ -460,11 +481,21 @@ As with other helpers, if you were to use the `select` helper on a form builder
|
|
460
481
|
<%= f.select(:city_id, ...) %>
|
461
482
|
```
|
462
483
|
|
463
|
-
|
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.
|
464
495
|
|
465
496
|
### Option Tags from a Collection of Arbitrary Objects
|
466
497
|
|
467
|
-
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:
|
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:
|
468
499
|
|
469
500
|
```erb
|
470
501
|
<% cities_array = City.all.map { |city| [city.name, city.id] } %>
|
@@ -483,6 +514,12 @@ As the name implies, this only generates option tags. To generate a working sele
|
|
483
514
|
<%= collection_select(:person, :city_id, City.all, :id, :name) %>
|
484
515
|
```
|
485
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
|
+
|
486
523
|
To recap, `options_from_collection_for_select` is to `collection_select` what `options_for_select` is to `select`.
|
487
524
|
|
488
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.
|
@@ -511,7 +548,7 @@ Both of these families of helpers will create a series of select boxes for the d
|
|
511
548
|
|
512
549
|
### Barebones Helpers
|
513
550
|
|
514
|
-
The `select_*` family of helpers take as their first argument an instance of Date
|
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:
|
515
552
|
|
516
553
|
```erb
|
517
554
|
<%= select_date Date.today, prefix: :start_date %>
|
@@ -525,7 +562,7 @@ outputs (with actual option values omitted for brevity)
|
|
525
562
|
<select id="start_date_day" name="start_date[day]"> ... </select>
|
526
563
|
```
|
527
564
|
|
528
|
-
The above inputs would result in `params[:start_date]` being a hash with keys `:year`, `:month`, `:day`. To get an actual Time or
|
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:
|
529
566
|
|
530
567
|
```ruby
|
531
568
|
Date.civil(params[:start_date][:year].to_i, params[:start_date][:month].to_i, params[:start_date][:day].to_i)
|
@@ -553,7 +590,7 @@ outputs (with actual option values omitted for brevity)
|
|
553
590
|
which results in a `params` hash like
|
554
591
|
|
555
592
|
```ruby
|
556
|
-
{
|
593
|
+
{'person' => {'birth_date(1i)' => '2008', 'birth_date(2i)' => '11', 'birth_date(3i)' => '22'}}
|
557
594
|
```
|
558
595
|
|
559
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`.
|
@@ -568,9 +605,9 @@ NOTE: In many cases the built-in date pickers are clumsy as they do not aid the
|
|
568
605
|
|
569
606
|
### Individual Components
|
570
607
|
|
571
|
-
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
|
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.
|
572
609
|
|
573
|
-
The first parameter specifies which value should be selected and can either be an instance of a Date
|
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:
|
574
611
|
|
575
612
|
```erb
|
576
613
|
<%= select_year(2009) %>
|
@@ -600,18 +637,18 @@ Rails provides the usual pair of helpers: the barebones `file_field_tag` and the
|
|
600
637
|
|
601
638
|
### What Gets Uploaded
|
602
639
|
|
603
|
-
The object in the `params` hash is an instance of a subclass of IO
|
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).
|
604
641
|
|
605
642
|
```ruby
|
606
643
|
def upload
|
607
644
|
uploaded_io = params[:person][:picture]
|
608
|
-
File.open(Rails.root.join('public', 'uploads', uploaded_io.original_filename), '
|
645
|
+
File.open(Rails.root.join('public', 'uploads', uploaded_io.original_filename), 'wb') do |file|
|
609
646
|
file.write(uploaded_io.read)
|
610
647
|
end
|
611
648
|
end
|
612
649
|
```
|
613
650
|
|
614
|
-
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](
|
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).
|
615
652
|
|
616
653
|
NOTE: If the user has not selected a file the corresponding parameter will be an empty string.
|
617
654
|
|
@@ -622,7 +659,7 @@ Unlike other forms making an asynchronous file upload form is not as simple as p
|
|
622
659
|
Customizing Form Builders
|
623
660
|
-------------------------
|
624
661
|
|
625
|
-
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
|
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:
|
626
663
|
|
627
664
|
```erb
|
628
665
|
<%= form_for @person do |f| %>
|
@@ -638,7 +675,7 @@ can be replaced with
|
|
638
675
|
<% end %>
|
639
676
|
```
|
640
677
|
|
641
|
-
by defining a LabellingFormBuilder class similar to the following:
|
678
|
+
by defining a `LabellingFormBuilder` class similar to the following:
|
642
679
|
|
643
680
|
```ruby
|
644
681
|
class LabellingFormBuilder < ActionView::Helpers::FormBuilder
|
@@ -656,17 +693,17 @@ The form builder used also determines what happens when you do
|
|
656
693
|
<%= render partial: f %>
|
657
694
|
```
|
658
695
|
|
659
|
-
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.
|
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.
|
660
697
|
|
661
698
|
Understanding Parameter Naming Conventions
|
662
699
|
------------------------------------------
|
663
700
|
|
664
|
-
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`
|
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`
|
665
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.
|
666
703
|
|
667
|
-
Fundamentally HTML forms don't know about any sort of structured data, all they generate is name
|
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.
|
668
705
|
|
669
|
-
TIP: You may find you can try out examples in this section faster by using the console to directly invoke
|
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,
|
670
707
|
|
671
708
|
```ruby
|
672
709
|
Rack::Utils.parse_query "name=fred&phone=0123456789"
|
@@ -675,7 +712,7 @@ Rack::Utils.parse_query "name=fred&phone=0123456789"
|
|
675
712
|
|
676
713
|
### Basic Structures
|
677
714
|
|
678
|
-
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
|
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:
|
679
716
|
|
680
717
|
```html
|
681
718
|
<input id="person_name" name="person[name]" type="text" value="Henry"/>
|
@@ -689,7 +726,7 @@ the `params` hash will contain
|
|
689
726
|
|
690
727
|
and `params[:person][:name]` will retrieve the submitted value in the controller.
|
691
728
|
|
692
|
-
Hashes can be nested as many levels as required, for example
|
729
|
+
Hashes can be nested as many levels as required, for example:
|
693
730
|
|
694
731
|
```html
|
695
732
|
<input id="person_address_city" name="person[address][city]" type="text" value="New York"/>
|
@@ -701,7 +738,7 @@ will result in the `params` hash being
|
|
701
738
|
{'person' => {'address' => {'city' => 'New York'}}}
|
702
739
|
```
|
703
740
|
|
704
|
-
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
|
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:
|
705
742
|
|
706
743
|
```html
|
707
744
|
<input name="person[phone_number][]" type="text"/>
|
@@ -709,11 +746,11 @@ Normally Rails ignores duplicate parameter names. If the parameter name contains
|
|
709
746
|
<input name="person[phone_number][]" type="text"/>
|
710
747
|
```
|
711
748
|
|
712
|
-
This would result in `params[:person][:phone_number]` being an array.
|
749
|
+
This would result in `params[:person][:phone_number]` being an array containing the inputted phone numbers.
|
713
750
|
|
714
751
|
### Combining Them
|
715
752
|
|
716
|
-
We can mix and match these two concepts.
|
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
|
717
754
|
|
718
755
|
```html
|
719
756
|
<input name="addresses[][line1]" type="text"/>
|
@@ -723,7 +760,7 @@ We can mix and match these two concepts. For example, one element of a hash migh
|
|
723
760
|
|
724
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.
|
725
762
|
|
726
|
-
There's a restriction, however, while hashes can be nested arbitrarily, only one level of "arrayness" is allowed. Arrays can be
|
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.
|
727
764
|
|
728
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.
|
729
766
|
|
@@ -737,7 +774,7 @@ You might want to render a form with a set of edit fields for each of a person's
|
|
737
774
|
<%= form_for @person do |person_form| %>
|
738
775
|
<%= person_form.text_field :name %>
|
739
776
|
<% @person.addresses.each do |address| %>
|
740
|
-
<%= person_form.fields_for address, index: address do |address_form|%>
|
777
|
+
<%= person_form.fields_for address, index: address.id do |address_form|%>
|
741
778
|
<%= address_form.text_field :city %>
|
742
779
|
<% end %>
|
743
780
|
<% end %>
|
@@ -760,9 +797,16 @@ This will result in a `params` hash that looks like
|
|
760
797
|
{'person' => {'name' => 'Bob', 'address' => {'23' => {'city' => 'Paris'}, '45' => {'city' => 'London'}}}}
|
761
798
|
```
|
762
799
|
|
763
|
-
Rails knows that all these inputs should be part of the person hash because you
|
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).
|
764
807
|
|
765
|
-
To create more intricate nestings, you can specify the first part of the input
|
808
|
+
To create more intricate nestings, you can specify the first part of the input
|
809
|
+
name (`person[address]` in the previous example) explicitly:
|
766
810
|
|
767
811
|
```erb
|
768
812
|
<%= fields_for 'person[address][primary]', address, index: address do |address_form| %>
|
@@ -788,21 +832,21 @@ As a shortcut you can append [] to the name and omit the `:index` option. This i
|
|
788
832
|
|
789
833
|
produces exactly the same output as the previous example.
|
790
834
|
|
791
|
-
Forms to
|
835
|
+
Forms to External Resources
|
792
836
|
---------------------------
|
793
837
|
|
794
|
-
|
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:
|
795
839
|
|
796
840
|
```erb
|
797
|
-
<%= form_tag 'http://farfar.away/form', authenticity_token: 'external_token'
|
841
|
+
<%= form_tag 'http://farfar.away/form', authenticity_token: 'external_token' do %>
|
798
842
|
Form contents
|
799
843
|
<% end %>
|
800
844
|
```
|
801
845
|
|
802
|
-
Sometimes when
|
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:
|
803
847
|
|
804
848
|
```erb
|
805
|
-
<%= form_tag 'http://farfar.away/form', authenticity_token: false
|
849
|
+
<%= form_tag 'http://farfar.away/form', authenticity_token: false do %>
|
806
850
|
Form contents
|
807
851
|
<% end %>
|
808
852
|
```
|
@@ -826,11 +870,11 @@ Or if you don't want to render an `authenticity_token` field:
|
|
826
870
|
Building Complex Forms
|
827
871
|
----------------------
|
828
872
|
|
829
|
-
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.
|
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.
|
830
874
|
|
831
875
|
### Configuring the Model
|
832
876
|
|
833
|
-
Active Record provides model level support
|
877
|
+
Active Record provides model level support via the `accepts_nested_attributes_for` method:
|
834
878
|
|
835
879
|
```ruby
|
836
880
|
class Person < ActiveRecord::Base
|
@@ -845,7 +889,7 @@ end
|
|
845
889
|
|
846
890
|
This creates an `addresses_attributes=` method on `Person` that allows you to create, update and (optionally) destroy addresses.
|
847
891
|
|
848
|
-
###
|
892
|
+
### Nested Forms
|
849
893
|
|
850
894
|
The following form allows a user to create a `Person` and its associated addresses.
|
851
895
|
|
@@ -868,38 +912,40 @@ The following form allows a user to create a `Person` and its associated address
|
|
868
912
|
```
|
869
913
|
|
870
914
|
|
871
|
-
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
|
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.
|
872
916
|
|
873
917
|
```ruby
|
874
918
|
def new
|
875
919
|
@person = Person.new
|
876
|
-
|
920
|
+
2.times { @person.addresses.build}
|
877
921
|
end
|
878
922
|
```
|
879
923
|
|
880
|
-
`fields_for` yields a form builder
|
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:
|
881
927
|
|
882
928
|
```ruby
|
883
929
|
{
|
884
|
-
|
885
|
-
|
886
|
-
|
887
|
-
|
888
|
-
|
889
|
-
|
890
|
-
|
891
|
-
|
892
|
-
|
893
|
-
|
894
|
-
|
895
|
-
}
|
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
|
+
}
|
896
941
|
}
|
942
|
+
}
|
897
943
|
}
|
898
944
|
```
|
899
945
|
|
900
946
|
The keys of the `:addresses_attributes` hash are unimportant, they need merely be different for each address.
|
901
947
|
|
902
|
-
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
|
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`.
|
903
949
|
|
904
950
|
### The Controller
|
905
951
|
|
@@ -914,9 +960,9 @@ def create
|
|
914
960
|
end
|
915
961
|
|
916
962
|
private
|
917
|
-
def person_params
|
918
|
-
|
919
|
-
end
|
963
|
+
def person_params
|
964
|
+
params.require(:person).permit(:name, addresses_attributes: [:id, :kind, :street])
|
965
|
+
end
|
920
966
|
```
|
921
967
|
|
922
968
|
### Removing Objects
|
@@ -930,7 +976,9 @@ class Person < ActiveRecord::Base
|
|
930
976
|
end
|
931
977
|
```
|
932
978
|
|
933
|
-
If the hash of attributes for an object contains the key `_destroy` with a value
|
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:
|
934
982
|
|
935
983
|
```erb
|
936
984
|
<%= form_for @person do |f| %>
|
@@ -938,7 +986,7 @@ If the hash of attributes for an object contains the key `_destroy` with a value
|
|
938
986
|
<ul>
|
939
987
|
<%= f.fields_for :addresses do |addresses_form| %>
|
940
988
|
<li>
|
941
|
-
<%= check_box :_destroy%>
|
989
|
+
<%= addresses_form.check_box :_destroy%>
|
942
990
|
<%= addresses_form.label :kind %>
|
943
991
|
<%= addresses_form.text_field :kind %>
|
944
992
|
...
|
@@ -973,4 +1021,4 @@ As a convenience you can instead pass the symbol `:all_blank` which will create
|
|
973
1021
|
|
974
1022
|
### Adding Fields on the Fly
|
975
1023
|
|
976
|
-
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
|
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.
|