Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
tree: 73ebb26ece
Fetching contributors…

Cannot retrieve contributors at this time

494 lines (348 sloc) 25.597 kb
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 others.
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).
Different Families of helpers
------------------------------
Most of Rails' form helpers are available in two forms.
Barebones helpers
~~~~~~~~~~~~~~~~~~
These just generate the appropriate markup. These have names ending in _tag such as `text_field_tag`, check_box_tag`. The first parameter to these is always the name of the input. This is the name under which value will appear in the `params` hash in the controller. For example if the form contains
---------------------------
<%= text_field_tag(:query) %>
---------------------------
then the controller code should use
---------------------------
params[:query]
---------------------------
to retrieve the value entered by the user.
Model object helpers
~~~~~~~~~~~~~~~~~~~~~
These are designed to work with a model object (commonly an Active Record object but this need not be the case). These lack the _tag suffix, from example `text_field`, `text_area`
For the latter the first parameter is the name of an instance variable and the second is the name of attribute to be edited. Rails will set the value of the input control to the current value of that attribute for the object and set an appropriate input name. If our controller has defined `@person` and that person's name is Henry then a form containing:
---------------------------
<%= text_field(:person, :name) %>
---------------------------
will produce output similar to
---------------------------
<input id="person_name" name="person[name]" type="text" value="Henry"/>
---------------------------
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`.
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, so -- 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 an options string:
----------------------------------------------------------------------------
<%= select_tag(:city_id, '<option value="1">Lisabon</option>...') %>
----------------------------------------------------------------------------
This is a start, but it doesn't dynamically create our option tags. 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: option text (city name) and option value (city id). It is often the case the the internal value (the one that the form actually submits) is the id of a corresponding database object but this does not have to be the case.
Knowing this, 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([['Lisabon', 1], ['Madrid', 2], ...], 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.
=======
[TIP]
============================================================================
The second argument to `options_for_select` must be exactly equal to the desired internal value. In particular if the internal 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.
============================================================================
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.
Consistent with other form helpers, when dealing with models we drop the `"_tag"` suffix from `select_tag` that we used in previous examples:
----------------------------------------------------------------------------
# controller:
@person = Person.new(:city_id => 2)
# view:
<%= select(:person, :city_id, [['Lisabon', 1], ['Madrid', 2], ...]) %>
----------------------------------------------------------------------------
Notice that the third parameter, the options array, is the same kind of argument we pass to `options_for_select`. One thing that we have as an advantage here is that we don't have to worry about pre-selecting the correct city if the user already has one -- Rails will do this for us by reading from `@person.city_id` attribute.
As before, if we were to use `select` helper on a form builder scoped to `@person` object, the syntax would be:
----------------------------------------------------------------------------
# select on a form builder
<%= f.select(:city_id, ...) %>
----------------------------------------------------------------------------
Option tags from a collection of arbitrary objects
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Until now we were generating option tags from nested arrays with the help of `options_for_select` method. Data in our array were raw values:
----------------------------------------------------------------------------
<%= options_for_select([['Lisabon', 1], ['Madrid', 2], ...]) %>
----------------------------------------------------------------------------
But what if we had a *City* model (perhaps an ActiveRecord one) and we wanted to generate option tags from a collection of those objects? One solution would be to make a nested array by iterating over them:
----------------------------------------------------------------------------
<% cities_array = City.find(:all).map { |city| [city.name, city.id] } %>
<%= options_for_select(cities_array) %>
----------------------------------------------------------------------------
This is a perfectly valid solution, but Rails provides us with 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:
----------------------------------------------------------------------------
<%= options_from_collection_for_select(City.all, :id, :name) %>
----------------------------------------------------------------------------
As the name implies, this only generates option tags. A method to go along with it is `collection_select`:
----------------------------------------------------------------------------
<%= collection_select(:person, :city_id, City.all, :id, :name) %>
----------------------------------------------------------------------------
To recap, `options_from_collection_for_select` are to `collection_select` what `options_for_select` are to `select`.
Time zone and country select
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
To leverage time zone support in Rails, we have to ask our 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 we can simply use the `time_zone_select` helper that already wraps this:
----------------------------------------------------------------------------
<%= time_zone_select(:person, :city_id) %>
----------------------------------------------------------------------------
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.
When it comes to country select, Rails _used_ to have the built-in helper `country_select` but was extracted to a plugin.
TODO: plugin URL
Miscellaneous
-------------
File upload form
~~~~~~~~~~~~~~~~
:multipart - If set to true, the enctype is set to "multipart/form-data".
Scoping out form controls with `fields_for`
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Creates a scope around a specific model object like `form_for`, but doesn’t create the form tags themselves. This makes `fields_for` suitable for specifying additional model objects in the same form:
Making custom form builders
~~~~~~~~~~~~~~~~~~~~~~~~~~~
You can also build forms using a customized FormBuilder class. Subclass FormBuilder and override or define some more helpers, then use your custom builder. For example, let’s say you made a helper to automatically add labels to form inputs.
----------------------------------------------------------------------------
<% form_for :person, @person, :url => { :action => "update" }, :builder => LabellingFormBuilder do |f| %>
<%= f.text_field :first_name %>
<%= f.text_field :last_name %>
<%= text_area :person, :biography %>
<%= check_box_tag "person[admin]", @person.company.admin? %>
<% end %>
----------------------------------------------------------------------------
* `form_for` within a namespace
----------------------------------------------------------------------------
select_tag(name, option_tags = nil, html_options = { :multiple, :disabled })
select(object, method, choices, options = {}, html_options = {})
options_for_select(container, selected = nil)
collection_select(object, method, collection, value_method, text_method, options = {}, html_options = {})
options_from_collection_for_select(collection, value_method, text_method, selected = nil)
time_zone_options_for_select(selected = nil, priority_zones = nil, model = ::ActiveSupport::TimeZone)
time_zone_select(object, method, priority_zones = nil, options = {}, html_options = {})
----------------------------------------------------------------------------
=======
...
Form builders
-------------
Jump to Line
Something went wrong with that request. Please try again.