aboutsummaryrefslogtreecommitdiffstats
path: root/railties/doc/guides/forms/form_helpers.txt
blob: 7b0aeb0ed9ab7c2003777f71e7ae75bd2866347b (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
Rails form helpers
==================
Mislav Marohnić <mislav.marohnic@gmail.com>

Forms in web applications are an essential interface for user input. They are also often considered the most complex elements of HTML. Rails deals away with these complexities by providing numerous 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.

In this guide we will:

* Create search forms and similar kind of generic forms not representing any specific model in your application;
* Make model-centric forms for creation and editing of specific database records;
* Generate select boxes from multiple types of data;
* Learn what makes a file upload form different;
* Build complex, multi-model forms.

NOTE: This guide is not intended to be a complete documentation of available form helpers and their arguments. Please visit http://api.rubyonrails.org/[the Rails API documentation] for a complete reference.


Basic forms
-----------

The most basic form helper is `form_tag`.

----------------------------------------------------------------------------
<% form_tag do %>
  Form contents
<% end %>
----------------------------------------------------------------------------

When called without arguments like this, it creates a form element that has the current page for action attribute and "POST" as method (some line breaks added for readability):

.Sample rendering of `form_tag`
----------------------------------------------------------------------------
<form action="/home/index" method="post">
  <div style="margin:0;padding:0">
    <input name="authenticity_token" type="hidden" value="f755bb0ed134b76c432144748a6d4b7a7ddf2b71" />
  </div>
  Form contents
</form>
----------------------------------------------------------------------------

If you carefully observe this output, you can see that the helper generated something we 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 which action isn't "GET" (provided that this security feature is enabled).

NOTE: Throughout this guide, this `div` with the hidden input will be stripped away to have clearer code samples.

Generic search form
~~~~~~~~~~~~~~~~~~~

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:

1. a form element with "GET" method,
2. a label for the input,
3. a text input element, and
4. a submit element.

IMPORTANT: Always use "GET" as the method for search forms. Benefits are many: users are able to bookmark a specific search and get back to it; browsers cache results of "GET" requests, but not "POST"; and other.

To create that, we will use `form_tag`, `label_tag`, `text_field_tag` and `submit_tag`, respectively.

.A basic search form
----------------------------------------------------------------------------
<% form_tag(search_path, :method => "get") do %>
  <%= label_tag(:q, "Search for:") %>
  <%= text_field_tag(:q) %>
  <%= submit_tag("Search") %>
<% end %>
----------------------------------------------------------------------------

[TIP]
============================================================================
`search_path` can be a named route specified in "routes.rb":

----------------------------------------------------------------------------
map.search "search", :controller => "search"
----------------------------------------------------------------------------
============================================================================

The above view code will result in the following markup:

.Search form HTML
----------------------------------------------------------------------------
<form action="/search" method="get">
  <label for="q">Search for:</label>
  <input id="q" name="q" type="text" />
  <input name="commit" type="submit" value="Search" />
</form>
----------------------------------------------------------------------------

Besides `text_field_tag` and `submit_tag`, there is a similar helper for _every_ form control in HTML.

TIP: For every form input, an ID attribute is generated from its name ("q" in our example). These IDs can be very useful for CSS styling or manipulation of form controls with JavaScript.

Multiple hashes in form helper attributes
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

By now we've seen that the `form_tag` helper accepts 2 arguments: the path for the action attribute and an options hash for parameters (like `:method`).

Identical to the `link_to` helper, the path argument doesn't have to be given as string or a named route. It can be a hash of URL parameters that Rails' routing mechanism will turn into a valid URL. Still, we cannot simply write this:

.A bad way to pass multiple hashes as method arguments
----------------------------------------------------------------------------
form_tag(:controller => "people", :action => "search", :method => "get")
# => <form action="/people/search?method=get" method="post">
----------------------------------------------------------------------------

Here we wanted to pass two hashes, but the Ruby interpreter sees only one hash, so Rails will construct a URL that we didn't want. The solution is to delimit the first hash (or both hashes) with curly brackets:

.The correct way of passing multiple hashes as arguments
----------------------------------------------------------------------------
form_tag({:controller => "people", :action => "search"}, :method => "get")
# => <form action="/people/search" method="get">
----------------------------------------------------------------------------

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.

WARNING: Do not delimit the second hash without doing so with the first hash, otherwise your method invocation will result in an ugly `expecting tASSOC` syntax error.

Checkboxes, radio buttons and other controls
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Checkboxes are form controls that give the user a set of options they can enable or disable:

----------------------------------------------------------------------------
<%= check_box_tag(:pet_dog) %>
  <%= label_tag(:pet_dog, "I own a dog") %>
<%= check_box_tag(:pet_cat) %>
  <%= label_tag(:pet_cat, "I own a cat") %>

output:

<input id="pet_dog" name="pet_dog" type="checkbox" value="1" />
  <label for="pet_dog">I own a dog</label>
<input id="pet_cat" name="pet_cat" type="checkbox" value="1" />
  <label for="pet_cat">I own a cat</label>
----------------------------------------------------------------------------

Radio buttons, while similar to checkboxes, are controls that specify a set of options in which they are mutually exclusive (user can only pick one):

----------------------------------------------------------------------------
<%= radio_button_tag(:age, "child") %>
  <%= label_tag(:age_child, "I am younger than 21") %>
<%= radio_button_tag(:age, "adult") %>
  <%= label_tag(:age_adult, "I'm over 21") %>

output:

<input id="age_child" name="age" type="radio" value="child" />
  <label for="age_child">I am younger than 21</label>
<input id="age_adult" name="age" type="radio" value="adult" />
  <label for="age_adult">I'm over 21</label>
----------------------------------------------------------------------------

IMPORTANT: Always use labels for each checkbox and radio button. They associate text with a specific option, while also providing a larger clickable region.

Other form controls we might mention are the text area, password input and hidden input:

----------------------------------------------------------------------------
<%= text_area_tag(:message, "Hi, nice site", :size => "24x6") %>
<%= password_field_tag(:password) %>
<%= hidden_field_tag(:parent_id, "5") %>

output:

<textarea id="message" name="message" cols="24" rows="6">Hi, nice site</textarea>
<input id="password" name="password" type="password" />
<input id="parent_id" name="parent_id" type="hidden" value="5" />
----------------------------------------------------------------------------

Hidden inputs are not shown to the user, but they hold data same as any textual input. Values inside them can be changed with JavaScript.

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.

How do forms with PUT or DELETE methods work?
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

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"). Still, most browsers _don't support_ methods other than "GET" and "POST" when it comes to submitting forms. How does this work, then?

Rails works around this issue by emulating other methods over POST with a hidden input named `"_method"` that is set to reflect the _real_ method:

----------------------------------------------------------------------------
form_tag(search_path, :method => "put")
  
output:

<form action="/search" method="post">
  <div style="margin:0;padding:0">
    <input name="_method" type="hidden" value="put" />
    <input name="authenticity_token" type="hidden" value="f755bb0ed134b76c432144748a6d4b7a7ddf2b71" />
  </div>
  ...
----------------------------------------------------------------------------

When parsing POSTed data, Rails will take into account the special `"_method"` parameter and act as if the HTTP method was the one specified inside it ("PUT" in this example).


Forms that deal with model attributes
-------------------------------------

When we're dealing with an actual model, we will use a different set of form helpers and have Rails take care of some details in the background. In the following examples we will handle an Article model. First, let us have the controller create one:

.articles_controller.rb
----------------------------------------------------------------------------
def new
  @article = Article.new
end
----------------------------------------------------------------------------

Now we switch to the view. The first thing to remember is that we should use `form_for` helper instead of `form_tag`, and that we should pass the model name and object as arguments:

.articles/new.html.erb
----------------------------------------------------------------------------
<% form_for :article, @article, :url => { :action => "create" } do |f| %>
  <%= f.text_field :title %>
  <%= f.text_area :body, :size => "60x12" %>
  <%= submit_tag "Create" %>
<% end %>
----------------------------------------------------------------------------

There are a few things to note here:

1. `:article` is the name of the model and `@article` is our record.
2. The URL for the action attribute is passed as a parameter named `:url`.
3. The `form_for` method yields *a form builder* object (the `f` variable).
4. Methods to create form controls are called *on* the form builder object `f` and *without* the `"_tag"` suffix (so `text_field_tag` becomes `f.text_field`).

The resulting HTML is:

----------------------------------------------------------------------------
<form action="/articles/create" method="post">
  <input id="article_title" name="article[title]" size="30" type="text" />
  <textarea id="article_body" name="article[body]" cols="60" rows="12"></textarea>
  <input name="commit" type="submit" value="Create" />
</form>
----------------------------------------------------------------------------

A nice thing about `f.text_field` and other helper methods is that they will pre-fill the form control with the value read from the corresponding attribute in the model. For example, if we created the article instance by supplying an initial value for the title in the controller:

----------------------------------------------------------------------------
@article = Article.new(:title => "Rails makes forms easy")
----------------------------------------------------------------------------

... the corresponding input will be rendered with a value:

----------------------------------------------------------------------------
<input id="post_title" name="post[title]" size="30" type="text" value="Rails makes forms easy" />
----------------------------------------------------------------------------

Relying on record identification
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

In the previous chapter we handled the Article model. This model is directly available to users of our application and, following the best practices for developing with Rails, we should declare it *a resource*.

When dealing with RESTful resources, our calls to `form_for` can get significantly easier if we rely on *record identification*. In short, we can just pass the model instance and have Rails figure out model name and the rest:

----------------------------------------------------------------------------
## Creating a new article
# long-style:
form_for(:article, @article, :url => articles_path)
# same thing, short-style (record identification gets used):
form_for(@article)

## Editing an existing article
# long-style:
form_for(:article, @article, :url => article_path(@article), :method => "put")
# short-style:
form_for(@article)
----------------------------------------------------------------------------

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?`.

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.