Rails form helpers
==================
Mislav Marohnić <mislav.marohnic@gmail.com>
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.
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 `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 and provide 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 wanted 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.
Making select boxes with ease
-----------------------------
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 from data stored in arrays or hashes.
Here is what our wanted markup might look like:
----------------------------------------------------------------------------
<select name="city_id" id="city_id">
<option value="1">Lisabon</option>
<option value="2">Madrid</option>
...
<option value="12">Berlin</option>
</select>
----------------------------------------------------------------------------
Here we have a list of cities where their names are presented to the user, but internally we want to handle just their IDs so we keep them in value attributes. Let's see how Rails can help out here.
The select tag and options
~~~~~~~~~~~~~~~~~~~~~~~~~~
The most generic helper is `select_tag`, which -- as the name implies -- simply generates the `SELECT` tag that encapsulates the options:
----------------------------------------------------------------------------
<%= select_tag(:city_id, '<option value="1">Lisabon</option>...') %>
----------------------------------------------------------------------------
This is a start, but it doesn't dynamically create our option tags. We had to pass them in as a string.
We can generate option tags with the `options_for_select` helper:
----------------------------------------------------------------------------
<%= options_for_select([['Lisabon', 1], ['Madrid', 2], ...]) %>
output:
<option value="1">Lisabon</option>
<option value="2">Madrid</option>
...
----------------------------------------------------------------------------
For input data we used a nested array where each element has two elements: visible value (name) and internal value (ID).
Now you can combine `select_tag` and `options_for_select` to achieve the desired, complete markup:
----------------------------------------------------------------------------
<%= select_tag(:city_id, options_for_select(...)) %>
----------------------------------------------------------------------------
Sometimes, depending on our application's needs, we also wish a specific option to be pre-selected. The `options_for_select` helper supports this with an optional second argument:
----------------------------------------------------------------------------
<%= options_for_select(cities_array, 2) %>
output:
<option value="1">Lisabon</option>
<option value="2" selected="selected">Madrid</option>
...
----------------------------------------------------------------------------
So whenever Rails sees that the internal value of an option being generated matches this value, it will add the `selected` attribute to that option.
Select boxes for dealing with models
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Until now we've covered how to make generic select boxes, but in most cases our form controls will be tied to a specific database model. So, to continue from our previous examples, let's assume that we have a "Person" model with a `city_id` attribute.
----------------------------------------------------------------------------
...
----------------------------------------------------------------------------
...