rails 2.3.8 → 2.3.9.pre

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.

Files changed (119) hide show
  1. data/CHANGELOG +3 -2
  2. data/Rakefile +6 -7
  3. data/builtin/rails_info/rails/info.rb +1 -1
  4. data/environments/boot.rb +6 -2
  5. data/environments/environment.rb +1 -1
  6. data/lib/initializer.rb +44 -20
  7. data/lib/rails/plugin.rb +1 -1
  8. data/lib/rails/plugin/loader.rb +3 -3
  9. data/lib/rails/version.rb +1 -1
  10. data/lib/rails_generator/generators/components/migration/migration_generator.rb +1 -1
  11. data/lib/rails_generator/generators/components/plugin/templates/test_helper.rb +2 -1
  12. metadata +25 -124
  13. data/guides/files/javascripts/code_highlighter.js +0 -188
  14. data/guides/files/javascripts/guides.js +0 -8
  15. data/guides/files/javascripts/highlighters.js +0 -90
  16. data/guides/files/stylesheets/main.css +0 -441
  17. data/guides/files/stylesheets/print.css +0 -52
  18. data/guides/files/stylesheets/reset.css +0 -43
  19. data/guides/files/stylesheets/style.css +0 -13
  20. data/guides/files/stylesheets/syntax.css +0 -31
  21. data/guides/images/belongs_to.png +0 -0
  22. data/guides/images/book_icon.gif +0 -0
  23. data/guides/images/bullet.gif +0 -0
  24. data/guides/images/chapters_icon.gif +0 -0
  25. data/guides/images/check_bullet.gif +0 -0
  26. data/guides/images/credits_pic_blank.gif +0 -0
  27. data/guides/images/csrf.png +0 -0
  28. data/guides/images/customized_error_messages.png +0 -0
  29. data/guides/images/error_messages.png +0 -0
  30. data/guides/images/feature_tile.gif +0 -0
  31. data/guides/images/footer_tile.gif +0 -0
  32. data/guides/images/fxn.jpg +0 -0
  33. data/guides/images/grey_bullet.gif +0 -0
  34. data/guides/images/habtm.png +0 -0
  35. data/guides/images/has_many.png +0 -0
  36. data/guides/images/has_many_through.png +0 -0
  37. data/guides/images/has_one.png +0 -0
  38. data/guides/images/has_one_through.png +0 -0
  39. data/guides/images/header_backdrop.png +0 -0
  40. data/guides/images/header_tile.gif +0 -0
  41. data/guides/images/i18n/demo_localized_pirate.png +0 -0
  42. data/guides/images/i18n/demo_translated_en.png +0 -0
  43. data/guides/images/i18n/demo_translated_pirate.png +0 -0
  44. data/guides/images/i18n/demo_translation_missing.png +0 -0
  45. data/guides/images/i18n/demo_untranslated.png +0 -0
  46. data/guides/images/icons/README +0 -5
  47. data/guides/images/icons/callouts/1.png +0 -0
  48. data/guides/images/icons/callouts/10.png +0 -0
  49. data/guides/images/icons/callouts/11.png +0 -0
  50. data/guides/images/icons/callouts/12.png +0 -0
  51. data/guides/images/icons/callouts/13.png +0 -0
  52. data/guides/images/icons/callouts/14.png +0 -0
  53. data/guides/images/icons/callouts/15.png +0 -0
  54. data/guides/images/icons/callouts/2.png +0 -0
  55. data/guides/images/icons/callouts/3.png +0 -0
  56. data/guides/images/icons/callouts/4.png +0 -0
  57. data/guides/images/icons/callouts/5.png +0 -0
  58. data/guides/images/icons/callouts/6.png +0 -0
  59. data/guides/images/icons/callouts/7.png +0 -0
  60. data/guides/images/icons/callouts/8.png +0 -0
  61. data/guides/images/icons/callouts/9.png +0 -0
  62. data/guides/images/icons/caution.png +0 -0
  63. data/guides/images/icons/example.png +0 -0
  64. data/guides/images/icons/home.png +0 -0
  65. data/guides/images/icons/important.png +0 -0
  66. data/guides/images/icons/next.png +0 -0
  67. data/guides/images/icons/note.png +0 -0
  68. data/guides/images/icons/prev.png +0 -0
  69. data/guides/images/icons/tip.png +0 -0
  70. data/guides/images/icons/up.png +0 -0
  71. data/guides/images/icons/warning.png +0 -0
  72. data/guides/images/nav_arrow.gif +0 -0
  73. data/guides/images/polymorphic.png +0 -0
  74. data/guides/images/posts_index.png +0 -0
  75. data/guides/images/rails_guides_logo.gif +0 -0
  76. data/guides/images/rails_logo_remix.gif +0 -0
  77. data/guides/images/rails_welcome.png +0 -0
  78. data/guides/images/session_fixation.png +0 -0
  79. data/guides/images/tab_grey.gif +0 -0
  80. data/guides/images/tab_info.gif +0 -0
  81. data/guides/images/tab_note.gif +0 -0
  82. data/guides/images/tab_red.gif +0 -0
  83. data/guides/images/tab_yellow.gif +0 -0
  84. data/guides/images/tab_yellow.png +0 -0
  85. data/guides/images/validation_error_messages.png +0 -0
  86. data/guides/rails_guides.rb +0 -42
  87. data/guides/rails_guides/generator.rb +0 -138
  88. data/guides/rails_guides/helpers.rb +0 -34
  89. data/guides/rails_guides/indexer.rb +0 -55
  90. data/guides/rails_guides/textile_extensions.rb +0 -41
  91. data/guides/source/2_2_release_notes.textile +0 -422
  92. data/guides/source/2_3_release_notes.textile +0 -610
  93. data/guides/source/action_controller_overview.textile +0 -776
  94. data/guides/source/action_mailer_basics.textile +0 -424
  95. data/guides/source/active_record_basics.textile +0 -135
  96. data/guides/source/active_record_querying.textile +0 -969
  97. data/guides/source/activerecord_validations_callbacks.textile +0 -1086
  98. data/guides/source/association_basics.textile +0 -1781
  99. data/guides/source/caching_with_rails.textile +0 -524
  100. data/guides/source/command_line.textile +0 -589
  101. data/guides/source/configuring.textile +0 -234
  102. data/guides/source/contribute.textile +0 -71
  103. data/guides/source/contributing_to_rails.textile +0 -239
  104. data/guides/source/credits.erb.textile +0 -52
  105. data/guides/source/debugging_rails_applications.textile +0 -709
  106. data/guides/source/form_helpers.textile +0 -766
  107. data/guides/source/getting_started.textile +0 -1297
  108. data/guides/source/i18n.textile +0 -912
  109. data/guides/source/index.erb.textile +0 -124
  110. data/guides/source/layout.html.erb +0 -103
  111. data/guides/source/layouts_and_rendering.textile +0 -979
  112. data/guides/source/migrations.textile +0 -591
  113. data/guides/source/nested_model_forms.textile +0 -222
  114. data/guides/source/performance_testing.textile +0 -531
  115. data/guides/source/plugins.textile +0 -1512
  116. data/guides/source/rails_on_rack.textile +0 -309
  117. data/guides/source/routing.textile +0 -903
  118. data/guides/source/security.textile +0 -986
  119. data/guides/source/testing.textile +0 -951
@@ -1,766 +0,0 @@
1
- h2. Rails Form helpers
2
-
3
- Forms in web applications are an essential interface for user input. However, form markup can quickly become tedious to write and maintain because of form control naming and their numerous attributes. Rails deals away with these complexities by providing view helpers for generating form markup. However, since they have different use-cases, developers are required to know all the differences between similar helper methods before putting them to use.
4
-
5
- In this guide you will:
6
-
7
- * Create search forms and similar kind of generic forms not representing any specific model in your application
8
- * Make model-centric forms for creation and editing of specific database records
9
- * Generate select boxes from multiple types of data
10
- * Understand the date and time helpers Rails provides
11
- * Learn what makes a file upload form different
12
- * Find out where to look for complex forms
13
-
14
- endprologue.
15
-
16
- 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.
17
-
18
-
19
- h3. Dealing with Basic Forms
20
-
21
- The most basic form helper is +form_tag+.
22
-
23
- <erb>
24
- <% form_tag do %>
25
- Form contents
26
- <% end %>
27
- </erb>
28
-
29
- When called without arguments like this, it creates a form element that has the current page as its action and "post" as its method (some line breaks added for readability):
30
-
31
- Sample output from +form_tag+:
32
-
33
- <html>
34
- <form action="/home/index" method="post">
35
- <div style="margin:0;padding:0">
36
- <input name="authenticity_token" type="hidden" value="f755bb0ed134b76c432144748a6d4b7a7ddf2b71" />
37
- </div>
38
- Form contents
39
- </form>
40
- </html>
41
-
42
- If you carefully observe this output, you can see that the helper generated something you didn't specify: a +div+ element with a hidden input inside. This is a security feature of Rails called *cross-site request forgery protection* and form helpers generate it for every form whose action is not "get" (provided that this security feature is enabled). You can read more about this in the "Ruby On Rails Security Guide":./security.html#_cross_site_reference_forgery_csrf.
43
-
44
- NOTE: Throughout this guide, this +div+ with the hidden input will be stripped away to have clearer code samples.
45
-
46
- h4. A Generic Search Form
47
-
48
- Probably the most minimal form often seen on the web is a search form with a single text input for search terms. This form consists of:
49
-
50
- # a form element with "GET" method,
51
- # a label for the input,
52
- # a text input element, and
53
- # a submit element.
54
-
55
- 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.
56
-
57
- To create this form you will use +form_tag+, +label_tag+, +text_field_tag+, and +submit_tag+, respectively.
58
-
59
- A basic search form
60
-
61
- <html>
62
- <% form_tag(search_path, :method => "get") do %>
63
- <%= label_tag(:q, "Search for:") %>
64
- <%= text_field_tag(:q) %>
65
- <%= submit_tag("Search") %>
66
- <% end %>
67
- </html>
68
-
69
- TIP: +search_path+ can be a named route specified in "routes.rb": <pre>map.search "search", :controller => "search"</pre>
70
-
71
- The above view code will result in the following markup:
72
-
73
- <html>
74
- <form action="/search" method="get">
75
- <label for="q">Search for:</label>
76
- <input id="q" name="q" type="text" />
77
- <input name="commit" type="submit" value="Search" />
78
- </form>
79
- </html>
80
-
81
- Besides +text_field_tag+ and +submit_tag+, there is a similar helper for _every_ form control in HTML.
82
-
83
- 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.
84
-
85
- h4. Multiple Hashes in Form Helper Calls
86
-
87
- By now you've seen that 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.
88
-
89
- As with the +link_to+ helper, the path argument doesn't have to be given a string. It can be a hash of URL parameters that Rails' routing mechanism will turn into a valid URL. However, this is a bad way to pass multiple hashes as method arguments:
90
-
91
- <ruby>
92
- form_tag(:controller => "people", :action => "search", :method => "get", :class => "nifty_form")
93
- # => <form action="/people/search?method=get&class=nifty_form" method="post">
94
- </ruby>
95
-
96
- Here you wanted to pass two hashes, but the Ruby interpreter sees only one hash, so Rails will construct a URL with extraneous parameters. The correct way of passing multiple hashes as arguments is to delimit the first hash (or both hashes) with curly brackets:
97
-
98
- <ruby>
99
- form_tag({:controller => "people", :action => "search"}, :method => "get", :class => "nifty_form")
100
- # => <form action="/people/search" method="get" class="nifty_form">
101
- </ruby>
102
-
103
- This is a common pitfall when using form helpers, since many of them accept multiple hashes. So in future, if a helper produces unexpected output, make sure that you have delimited the hash parameters properly.
104
-
105
- WARNING: Do not delimit the second hash without doing so with the first hash, otherwise your method invocation will result in an +expecting tASSOC+ syntax error.
106
-
107
- h4. Helpers for Generating Form Elements
108
-
109
- Rails provides a series of helpers for generating form elements such as checkboxes, text fields, radio buttons, and so on. These basic helpers, with names ending in <notextile>_tag</notextile> such as +text_field_tag+, +check_box_tag+, etc., generate just a single +&lt;input&gt;+ element. The first parameter to these is always the name of the input. In the controller this name will be the key in the +params+ hash used to get the value entered by the user. For example, if the form contains
110
-
111
- <erb>
112
- <%= text_field_tag(:query) %>
113
- </erb>
114
-
115
- then the controller code should use
116
-
117
- <ruby>
118
- params[:query]
119
- </ruby>
120
-
121
- to retrieve the value entered by the user. When naming inputs, be aware that Rails uses certain conventions that control whether values are at the top level of the +params+ hash, inside an array or a nested hash and so on. You can read more about them in the parameter_names section. For details on the precise usage of these helpers, please refer to the "API documentation":http://api.rubyonrails.org/classes/ActionView/Helpers/FormTagHelper.html.
122
-
123
- h5. Checkboxes
124
-
125
- Checkboxes are form controls that give the user a set of options they can enable or disable:
126
-
127
- <erb>
128
- <%= check_box_tag(:pet_dog) %>
129
- <%= label_tag(:pet_dog, "I own a dog") %>
130
- <%= check_box_tag(:pet_cat) %>
131
- <%= label_tag(:pet_cat, "I own a cat") %>
132
-
133
- output:
134
-
135
- <input id="pet_dog" name="pet_dog" type="checkbox" value="1" />
136
- <label for="pet_dog">I own a dog</label>
137
- <input id="pet_cat" name="pet_cat" type="checkbox" value="1" />
138
- <label for="pet_cat">I own a cat</label>
139
- </erb>
140
-
141
- The second parameter to +check_box_tag+ is the value of the input. This is the value that will be submitted by the browser if the checkbox is ticked (i.e. the value that will be present in the +params+ hash). With the above form you would check the value of +params[:pet_dog]+ and +params[:pet_cat]+ to see which pets the user owns.
142
-
143
- h5. Radio Buttons
144
-
145
- 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):
146
-
147
- <erb>
148
- <%= radio_button_tag(:age, "child") %>
149
- <%= label_tag(:age_child, "I am younger than 21") %>
150
- <%= radio_button_tag(:age, "adult") %>
151
- <%= label_tag(:age_adult, "I'm over 21") %>
152
-
153
- output:
154
-
155
- <input id="age_child" name="age" type="radio" value="child" />
156
- <label for="age_child">I am younger than 21</label>
157
- <input id="age_adult" name="age" type="radio" value="adult" />
158
- <label for="age_adult">I'm over 21</label>
159
- </erb>
160
-
161
- 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".
162
-
163
- IMPORTANT: Always use labels for each checkbox and radio button. They associate text with a specific option and provide a larger clickable region.
164
-
165
- h4. Other Helpers of Interest
166
-
167
- Other form controls worth mentioning are the text area, password input and hidden input:
168
-
169
- <erb>
170
- <%= text_area_tag(:message, "Hi, nice site", :size => "24x6") %>
171
- <%= password_field_tag(:password) %>
172
- <%= hidden_field_tag(:parent_id, "5") %>
173
-
174
- output:
175
-
176
- <textarea id="message" name="message" cols="24" rows="6">Hi, nice site</textarea>
177
- <input id="password" name="password" type="password" />
178
- <input id="parent_id" name="parent_id" type="hidden" value="5" />
179
- </erb>
180
-
181
- Hidden inputs are not shown to the user, but they hold data like any textual input. Values inside them can be changed with JavaScript.
182
-
183
- TIP: If you're using password input fields (for any purpose), you might want to prevent their values showing up in application logs by activating +filter_parameter_logging(:password)+ in your ApplicationController.
184
-
185
-
186
- h3. Dealing with Model Objects
187
-
188
- h4. Model Object Helpers
189
-
190
- 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 <notextile>_tag</notextile> suffix, for example +text_field+, +text_area+.
191
-
192
- 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:
193
-
194
- <erb>
195
- <%= text_field(:person, :name) %>
196
- </erb>
197
-
198
- will produce output similar to
199
-
200
- <erb>
201
- <input id="person_name" name="person[name]" type="text" value="Henry"/>
202
- </erb>
203
-
204
- 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_attributes+. 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.
205
-
206
- WARNING: You must pass the name of an instance variable, i.e. +:person+ or +"person"+, not an actual instance of your model object.
207
-
208
- Rails provides helpers for displaying the validation errors associated with a model object. These are covered in detail by the "Active Record Validations and Callbacks":./activerecord_validations_callbacks.html#_using_the_tt_errors_tt_collection_in_your_view_templates guide.
209
-
210
- h4. Binding a Form to an Object
211
-
212
- 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.
213
-
214
- Assume we have a controller for dealing with articles:
215
-
216
- articles_controller.rb:
217
-
218
- <ruby>
219
- def new
220
- @article = Article.new
221
- end
222
- </ruby>
223
-
224
- The corresponding view using +form_for+ looks like this
225
-
226
- articles/new.html.erb:
227
-
228
- <erb>
229
- <% form_for :article, @article, :url => { :action => "create" }, :html => {:class => "nifty_form"} do |f| %>
230
- <%= f.text_field :title %>
231
- <%= f.text_area :body, :size => "60x12" %>
232
- <%= submit_tag "Create" %>
233
- <% end %>
234
- </erb>
235
-
236
- There are a few things to note here:
237
-
238
- # +:article+ is the name of the model and +@article+ is the actual object being edited.
239
- # There is a single hash of options. Routing options are passed in the +:url+ hash, HTML options are passed in the +:html+ hash.
240
- # The +form_for+ method yields a *form builder* object (the +f+ variable).
241
- # Methods to create form controls are called *on* the form builder object +f+
242
-
243
- The resulting HTML is:
244
-
245
- <html>
246
- <form action="/articles/create" method="post" class="nifty_form">
247
- <input id="article_title" name="article[title]" size="30" type="text" />
248
- <textarea id="article_body" name="article[body]" cols="60" rows="12"></textarea>
249
- <input name="commit" type="submit" value="Create" />
250
- </form>
251
- </html>
252
-
253
- 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[<em>attribute_name</em>]+. 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.
254
-
255
- 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.
256
-
257
- You can create a similar binding without actually creating +&lt;form&gt;+ 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:
258
-
259
- <erb>
260
- <% form_for :person, @person, :url => { :action => "create" } do |person_form| %>
261
- <%= person_form.text_field :name %>
262
- <% fields_for @person.contact_detail do |contact_details_form| %>
263
- <%= contact_details_form.text_field :phone_number %>
264
- <% end %>
265
- <% end %>
266
- </erb>
267
-
268
- which produces the following output:
269
-
270
- <html>
271
- <form action="/people/create" class="new_person" id="new_person" method="post">
272
- <input id="person_name" name="person[name]" size="30" type="text" />
273
- <input id="contact_detail_phone_number" name="contact_detail[phone_number]" size="30" type="text" />
274
- </form>
275
- </html>
276
-
277
- 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).
278
-
279
- h4. Relying on Record Identification
280
-
281
- 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*.
282
-
283
- 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:
284
-
285
- <ruby>
286
- ## Creating a new article
287
- # long-style:
288
- form_for(:article, @article, :url => articles_path)
289
- # same thing, short-style (record identification gets used):
290
- form_for(@article)
291
-
292
- ## Editing an existing article
293
- # long-style:
294
- form_for(:article, @article, :url => article_path(@article), :method => "put")
295
- # short-style:
296
- form_for(@article)
297
- </ruby>
298
-
299
- 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.
300
-
301
- 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.
302
-
303
- 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.
304
-
305
- h5. Dealing with Namespaces
306
-
307
- If you have created namespaced routes, +form_for+ has a nifty shorthand for that too. If your application has an admin namespace then
308
-
309
- <ruby>
310
- form_for [:admin, @article]
311
- </ruby>
312
-
313
- will create a form that submits to the articles controller 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:
314
-
315
- <ruby>
316
- form_for [:admin, :management, @article]
317
- </ruby>
318
-
319
- For more information on Rails' routing system and the associated conventions, please see the "routing guide":./routing_outside_in.html.
320
-
321
-
322
- h4. How do forms with PUT or DELETE methods work?
323
-
324
- The Rails framework encourages RESTful design of your applications, which means you'll be making a lot of "PUT" 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.
325
-
326
- 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:
327
-
328
- <ruby>
329
- form_tag(search_path, :method => "put")
330
- </ruby>
331
-
332
- output:
333
-
334
- <html>
335
- <form action="/search" method="post">
336
- <div style="margin:0;padding:0">
337
- <input name="_method" type="hidden" value="put" />
338
- <input name="authenticity_token" type="hidden" value="f755bb0ed134b76c432144748a6d4b7a7ddf2b71" />
339
- </div>
340
- ...
341
- </html>
342
-
343
- 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 ("PUT" in this example).
344
-
345
-
346
- h3. Making Select Boxes with Ease
347
-
348
- 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.
349
-
350
- Here is what the markup might look like:
351
-
352
- <html>
353
- <select name="city_id" id="city_id">
354
- <option value="1">Lisbon</option>
355
- <option value="2">Madrid</option>
356
- ...
357
- <option value="12">Berlin</option>
358
- </select>
359
- </html>
360
-
361
- 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.
362
-
363
- h4. The Select and Option Tags
364
-
365
- The most generic helper is +select_tag+, which -- as the name implies -- simply generates the +SELECT+ tag that encapsulates an options string:
366
-
367
- <erb>
368
- <%= select_tag(:city_id, '<option value="1">Lisbon</option>...') %>
369
- </erb>
370
-
371
- This is a start, but it doesn't dynamically create the option tags. You can generate option tags with the +options_for_select+ helper:
372
-
373
- <erb>
374
- <%= options_for_select([['Lisbon', 1], ['Madrid', 2], ...]) %>
375
-
376
- output:
377
-
378
- <option value="1">Lisbon</option>
379
- <option value="2">Madrid</option>
380
- ...
381
- </erb>
382
-
383
- 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.
384
-
385
- Knowing this, you can combine +select_tag+ and +options_for_select+ to achieve the desired, complete markup:
386
-
387
- <erb>
388
- <%= select_tag(:city_id, options_for_select(...)) %>
389
- </erb>
390
-
391
- +options_for_select+ allows you to pre-select an option by passing its value.
392
-
393
- <erb>
394
- <%= options_for_select([['Lisbon', 1], ['Madrid', 2], ...], 2) %>
395
-
396
- output:
397
-
398
- <option value="1">Lisbon</option>
399
- <option value="2" selected="selected">Madrid</option>
400
- ...
401
- </erb>
402
-
403
- Whenever Rails sees that the internal value of an option being generated matches this value, it will add the +selected+ attribute to that option.
404
-
405
- 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.
406
-
407
- h4. Select Boxes for Dealing with Models
408
-
409
- 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+:
410
-
411
- <ruby>
412
- # controller:
413
- @person = Person.new(:city_id => 2)
414
- </ruby>
415
-
416
- <erb>
417
- # view:
418
- <%= select(:person, :city_id, [['Lisbon', 1], ['Madrid', 2], ...]) %>
419
- </erb>
420
-
421
- 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.
422
-
423
- 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:
424
-
425
- <erb>
426
- # select on a form builder
427
- <%= f.select(:city_id, ...) %>
428
- </erb>
429
-
430
- 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 <pre> ActiveRecord::AssociationTypeMismatch: City(#17815740) expected, got String(#1138750) </pre> when you pass the +params+ hash to +Person.new+ or +update_attributes+. Another way of looking at this is that form helpers only edit attributes. You should also be aware of the potential security ramifications of allowing users to edit foreign keys directly. You may wish to consider the use of +attr_protected+ and +attr_accessible+. For further details on this, see the "Ruby On Rails Security Guide":security.html#_mass_assignment.
431
-
432
- h4. Option Tags from a Collection of Arbitrary Objects
433
-
434
- 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:
435
-
436
- <erb>
437
- <% cities_array = City.all.map { |city| [city.name, city.id] } %>
438
- <%= options_for_select(cities_array) %>
439
- </erb>
440
-
441
- 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:
442
-
443
- <erb>
444
- <%= options_from_collection_for_select(City.all, :id, :name) %>
445
- </erb>
446
-
447
- 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+.
448
-
449
- <erb>
450
- <%= collection_select(:person, :city_id, City.all, :id, :name) %>
451
- </erb>
452
-
453
- To recap, +options_from_collection_for_select+ is to +collection_select+ what +options_for_select+ is to +select+.
454
-
455
- 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.
456
-
457
- h4. Time Zone and Country Select
458
-
459
- 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:
460
-
461
- <erb>
462
- <%= time_zone_select(:person, :time_zone) %>
463
- </erb>
464
-
465
- 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.
466
-
467
- Rails _used_ to have a +country_select+ helper for choosing countries, but this has been extracted to the "country_select plugin":http://github.com/rails/country_select/tree/master. 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).
468
-
469
- h3. Using Date and Time Form Helpers
470
-
471
- The date and time helpers differ from all the other form helpers in two important respects:
472
-
473
- # 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.
474
- # 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.
475
-
476
- Both of these families of helpers will create a series of select boxes for the different components (year, month, day etc.).
477
-
478
- h4. Barebones Helpers
479
-
480
- 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
481
-
482
- <erb>
483
- <%= select_date Date.today, :prefix => :start_date %>
484
- </erb>
485
-
486
- outputs (with actual option values omitted for brevity)
487
-
488
- <html>
489
- <select id="start_date_year" name="start_date[year]"> ... </select>
490
- <select id="start_date_month" name="start_date[month]"> ... </select>
491
- <select id="start_date_day" name="start_date[day]"> ... </select>
492
- </html>
493
-
494
- 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
495
-
496
- <ruby>
497
- Date.civil(params[:start_date][:year].to_i, params[:start_date][:month].to_i, params[:start_date][:day].to_i)
498
- </ruby>
499
-
500
- 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+.
501
-
502
- h4. Model Object Helpers
503
-
504
- +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.
505
- 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:
506
-
507
- <erb>
508
- <%= date_select :person, :birth_date %>
509
- </erb>
510
-
511
- outputs (with actual option values omitted for brevity)
512
-
513
- <html>
514
- <select id="person_birth_date_1i" name="person[birth_date(1i)]"> ... </select>
515
- <select id="person_birth_date_2i" name="person[birth_date(2i)]"> ... </select>
516
- <select id="person_birth_date_3i" name="person[birth_date(3i)]"> ... </select>
517
- </html>
518
-
519
- which results in a +params+ hash like
520
-
521
- <ruby>
522
- {:person => {'birth_date(1i)' => '2008', 'birth_date(2i)' => '11', 'birth_date(3i)' => '22'}}
523
- </ruby>
524
-
525
- When this is passed to +Person.new+ (or +update_attributes+), 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+.
526
-
527
- h4. Common Options
528
-
529
- 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.
530
-
531
- 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.
532
-
533
- 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.
534
-
535
- h4. Individual Components
536
-
537
- 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 overriden 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.
538
-
539
- 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
540
-
541
- <erb>
542
- <%= select_year(2009) %>
543
- <%= select_year(Time.now) %>
544
- </erb>
545
-
546
- 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]+.
547
-
548
- h3. Uploading Files
549
-
550
- 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 form's encoding *MUST* be set to "multipart/form-data". If you forget to do this the file will not be uploaded. This can be done by passing +:multi_part => true+ as an HTML option. This means that in the case of +form_tag+ it must be passed in the second options hash and in the case of +form_for+ inside the +:html+ hash.
551
-
552
- The following two forms both upload a file.
553
-
554
- <erb>
555
- <% form_tag({:action => :upload}, :multipart => true) do %>
556
- <%= file_field_tag 'picture' %>
557
- <% end %>
558
-
559
- <% form_for @person, :html => {:multipart => true} do |f| %>
560
- <%= f.file_field :picture %>
561
- <% end %>
562
- </erb>
563
-
564
- 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]+.
565
-
566
- h4. What Gets Uploaded
567
-
568
- 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).
569
-
570
- <ruby>
571
- def upload
572
- uploaded_io = params[:person][:picture]
573
- File.open(Rails.root.join('public', 'uploads', uploaded_io.original_filename), 'w') do |file|
574
- file.write(uploaded_io.read)
575
- end
576
- end
577
- </ruby>
578
-
579
- 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 plugins designed to assist with these. Two of the better known ones are "Attachment-Fu":http://github.com/technoweenie/attachment_fu and "Paperclip":http://www.thoughtbot.com/projects/paperclip.
580
-
581
- NOTE: If the user has not selected a file the corresponding parameter will be an empty string.
582
-
583
- h4. Dealing with Ajax
584
-
585
- Unlike other forms making an asynchronous file upload form is not as simple as replacing +form_for+ with +remote_form_for+. 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.
586
-
587
- h3. Customising Form Builders
588
-
589
- 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
590
-
591
- <erb>
592
- <% form_for @person do |f| %>
593
- <%= text_field_with_label f, :first_name %>
594
- <% end %>
595
- </erb>
596
-
597
- can be replaced with
598
-
599
- <erb>
600
- <% form_for @person, :builder => LabellingFormBuilder do |f| %>
601
- <%= f.text_field :first_name %>
602
- <% end %>
603
- </erb>
604
-
605
- by defining a LabellingFormBuilder class similar to the following:
606
-
607
- <ruby>
608
- class LabellingFormBuilder < ActionView::Helpers::FormBuilder
609
- def text_field(attribute, options={})
610
- label(attribute) + super
611
- end
612
- end
613
- </ruby>
614
-
615
- If you reuse this frequently you could define a +labeled_form_for+ helper that automatically applies the +:builder => LabellingFormBuilder+ option.
616
-
617
- The form builder used also determines what happens when you do
618
-
619
- <erb>
620
- <%= render :partial => f %>
621
- </erb>
622
-
623
- 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.
624
-
625
- h3. Understanding Parameter Naming Conventions
626
-
627
- 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+
628
- action for a Person model, +params[:model]+ 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.
629
-
630
- 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.
631
-
632
- TIP: You may find you can try out examples in this section faster by using the console to directly invoke Rails' parameter parser. For example <pre> ActionController::UrlEncodedPairParser.parse_query_parameters "name=fred&phone=0123456789" # => {"name"=>"fred", "phone"=>"0123456789"} </pre>
633
-
634
- h4. Basic Structures
635
-
636
- 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
637
-
638
- <html>
639
- <input id="person_name" name="person[name]" type="text" value="Henry"/>
640
- </html>
641
-
642
- the +params+ hash will contain
643
-
644
- <erb>
645
- {'person' => {'name' => 'Henry'}}
646
- </erb>
647
-
648
- and +params["name"]+ will retrieve the submitted value in the controller.
649
-
650
- Hashes can be nested as many levels as required, for example
651
-
652
- <html>
653
- <input id="person_address_city" name="person[address][city]" type="text" value="New York"/>
654
- </html>
655
-
656
- will result in the +params+ hash being
657
-
658
- <ruby>
659
- {'person' => {'address' => {'city' => 'New York'}}}
660
- </ruby>
661
-
662
- 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:
663
-
664
- <html>
665
- <input name="person[phone_number][]" type="text"/>
666
- <input name="person[phone_number][]" type="text"/>
667
- <input name="person[phone_number][]" type="text"/>
668
- </html>
669
-
670
- This would result in +params[:person][:phone_number]+ being an array.
671
-
672
- h4. Combining Them
673
-
674
- 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
675
-
676
- <html>
677
- <input name="addresses[][line1]" type="text"/>
678
- <input name="addresses[][line2]" type="text"/>
679
- <input name="addresses[][city]" type="text"/>
680
- </html>
681
-
682
- 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.
683
-
684
- 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.
685
-
686
- 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 a second 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.
687
-
688
- h4. Using Form Helpers
689
-
690
- 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.
691
-
692
- You might want to render a form with a set of edit fields for each of a person's addresses. For example:
693
-
694
- <erb>
695
- <% form_for @person do |person_form| %>
696
- <%= person_form.text_field :name %>
697
- <% for address in @person.addresses %>
698
- <% person_form.fields_for address, :index => address do |address_form|%>
699
- <%= address_form.text_field :city %>
700
- <% end %>
701
- <% end %>
702
- <% end %>
703
- </erb>
704
-
705
- Assuming the person had two addresses, with ids 23 and 45 this would create output similar to this:
706
-
707
- <html>
708
- <form action="/people/1" class="edit_person" id="edit_person_1" method="post">
709
- <input id="person_name" name="person[name]" size="30" type="text" />
710
- <input id="person_address_23_city" name="person[address][23][city]" size="30" type="text" />
711
- <input id="person_address_45_city" name="person[address][45][city]" size="30" type="text" />
712
- </form>
713
- </html>
714
-
715
- This will result in a +params+ hash that looks like
716
-
717
- <ruby>
718
- {'person' => {'name' => 'Bob', 'address' => {'23' => {'city' => 'Paris'}, '45' => {'city' => 'London'}}}}
719
- </ruby>
720
-
721
- Rails knows that all these inputs should be part of the person hash because you called +fields_for+ on the first form builder. By specifying an +:index+ option you're telling rails that instead of naming the inputs +person[address][city]+ it should insert that index surrounded by [] between the address and the city. If you pass an Active Record object as we did then Rails will call +to_param+ on it, which by default returns the database id. This is often useful as it is then easy to locate which Address record should be modified. You can pass numbers with some other significance, strings or even +nil+ (which will result in an array parameter being created).
722
-
723
- To create more intricate nestings, you can specify the first part of the input name (+person[address]+ in the previous example) explicitly, for example
724
-
725
- <erb>
726
- <% fields_for 'person[address][primary]', address, :index => address do |address_form| %>
727
- <%= address_form.text_field :city %>
728
- <% end %>
729
- </erb>
730
-
731
- will create inputs like
732
-
733
- <html>
734
- <input id="person_address_primary_1_city" name="person[address][primary][1][city]" size="30" type="text" value="bologna" />
735
- </html>
736
-
737
- 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.
738
-
739
- As a shortcut you can append [] to the name and omit the +:index+ option. This is the same as specifing +:index => address+ so
740
-
741
- <erb>
742
- <% fields_for 'person[address][primary][]', address do |address_form| %>
743
- <%= address_form.text_field :city %>
744
- <% end %>
745
- </erb>
746
-
747
- produces exactly the same output as the previous example.
748
-
749
- h3. Building Complex Forms
750
-
751
- Many apps grow beyond simple forms editing a single object. For example when creating a Person you might want to allow the user to (on the same form) create multiple address records (home, work, etc.). When later editing that person the user should be able to add, remove or amend addresses as necessary. While this guide has shown you all the pieces necessary to handle this, Rails does not yet have a standard end-to-end way of accomplishing this, but many have come up with viable approaches. These include:
752
-
753
- * Ryan Bates' series of railscasts on "complex forms":http://railscasts.com/episodes/75
754
- * Handle Multiple Models in One Form from "Advanced Rails Recipes":http://media.pragprog.com/titles/fr_arr/multiple_models_one_form.pdf
755
- * Eloy Duran's "nested_params":http://github.com/alloy/complex-form-examples/tree/alloy-nested_params plugin
756
- * Lance Ivy's "nested_assignment":http://github.com/cainlevy/nested_assignment/tree/master plugin and "sample application":http://github.com/cainlevy/complex-form-examples/tree/cainlevy
757
- * James Golick's "attribute_fu":http://github.com/giraffesoft/attribute_fu/tree plugin
758
-
759
- h3. Changelog
760
-
761
- "Lighthouse ticket":http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/1
762
-
763
- h3. Authors
764
-
765
- * Mislav Marohnić <mislav.marohnic@gmail.com>
766
- * "Frederick Cheung":credits.html#fcheung