diff options
Diffstat (limited to 'railties/doc/guides/source/form_helpers.txt')
-rw-r--r-- | railties/doc/guides/source/form_helpers.txt | 464 |
1 files changed, 382 insertions, 82 deletions
diff --git a/railties/doc/guides/source/form_helpers.txt b/railties/doc/guides/source/form_helpers.txt index d09ad15a90..d60ed10a39 100644 --- a/railties/doc/guides/source/form_helpers.txt +++ b/railties/doc/guides/source/form_helpers.txt @@ -4,13 +4,12 @@ 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: +In this guide you 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. @@ -28,7 +27,7 @@ The most basic form helper is `form_tag`. 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` +.Sample output from `form_tag` ---------------------------------------------------------------------------- <form action="/home/index" method="post"> <div style="margin:0;padding:0"> @@ -38,7 +37,7 @@ When called without arguments like this, it creates a form element that has the </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). +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 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. @@ -52,9 +51,9 @@ Probably the most minimal form often seen on the web is a search form with a sin 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. +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. +To create that, you will use `form_tag`, `label_tag`, `text_field_tag` and `submit_tag`, respectively. .A basic search form ---------------------------------------------------------------------------- @@ -87,27 +86,27 @@ The above view code will result in the following markup: 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. +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. 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`). +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. -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: +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. Still, you 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"> +form_tag(:controller => "people", :action => "search", :method => "get", :class => "nifty_form") +# => <form action="/people/search?method=get&class=nifty_form" 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: +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 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"> +form_tag({:controller => "people", :action => "search"}, :method => "get", :class => "nifty_form") +# => <form action="/people/search" method="get" class="nifty_form"> ---------------------------------------------------------------------------- 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. @@ -151,7 +150,7 @@ output: 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: +Other form controls worth mentioning are the text area, password input and hidden input: ---------------------------------------------------------------------------- <%= text_area_tag(:message, "Hi, nice site", :size => "24x6") %> @@ -174,7 +173,7 @@ 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: +Rails works around this issue by emulating other methods over POST with a hidden input named `"_method"` that is set to reflect the desired method: ---------------------------------------------------------------------------- form_tag(search_path, :method => "put") @@ -189,13 +188,49 @@ output: ... ---------------------------------------------------------------------------- -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). +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. When naming inputs be aware that Rails uses certain conventions that control whether values appear 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,parameter names>> section. For details on the precise usage of these helpers, please refer to the http://api.rubyonrails.org/classes/ActionView/Helpers/FormTagHelper.html[API documentation]. + +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, for example `text_field`, `text_area`. + +For these helpers the first arguement is the name of an instance variable and the second is the name 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: + +--------------------------- +<%= text_field(:person, :name) %> +--------------------------- +will produce output similar to +--------------------------- +<input id="person_name" name="person[name]" type="text" value="Henry"/> +--------------------------- +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`. + +[WARNING] +============================================================================ +You must pass the name of an instance variable, i.e. `:person` or `"person"`, not an actual instance of your model object. +============================================================================ 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: +While the helpers seen so far are handy Rails can save you some work. For example typically a form is used to edit multiple attributes of a single object, so having to repeat the name of the object being edited is clumsy. The following examples will handle an Article model. First, have the controller create one: .articles_controller.rb ---------------------------------------------------------------------------- @@ -204,11 +239,11 @@ def 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: +Now switch to the view. The first thing to remember is to use the `form_for` helper instead of `form_tag`, and that you should pass the model name and object as arguments: .articles/new.html.erb ---------------------------------------------------------------------------- -<% form_for :article, @article, :url => { :action => "create" } do |f| %> +<% form_for :article, @article, :url => { :action => "create" }, :html => {:class => "nifty_form"} do |f| %> <%= f.text_field :title %> <%= f.text_area :body, :size => "60x12" %> <%= submit_tag "Create" %> @@ -217,39 +252,30 @@ Now we switch to the view. The first thing to remember is that we should use `fo 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`. +1. `:article` is the name of the model and `@article` is the record. +2. There is a single hash of options. Routing options are passed inside `:url` hash, HTML options are passed in the `:html` hash. 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`). +4. Methods to create form controls are called *on* the form builder object `f` The resulting HTML is: ---------------------------------------------------------------------------- -<form action="/articles/create" method="post"> +<form action="/articles/create" method="post" class="nifty_form"> <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> ---------------------------------------------------------------------------- +The name passed to `form_for` controls where in the params hash the form values will appear. Here the name is `article` and so all the inputs have names of the form `article[attribute_name]`. 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,parameter names>> section. -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" /> ----------------------------------------------------------------------------- +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. 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*. +In the previous chapter you handled the Article model. This model is directly available to users of our application, so -- following the best practices for developing with Rails -- you 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: +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: ---------------------------------------------------------------------------- ## Creating a new article @@ -265,10 +291,26 @@ form_for(:article, @article, :url => article_path(@article), :method => "put") 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?`. +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. + +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`. The attributes will be omitted or brevity in the rest of this guide. 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. +Dealing with namespaces +^^^^^^^^^^^^^^^^^^^^^^^ + +If you have created namespaced routes `form_for` has a nifty shorthand for that too. If your application has an admin namespace then +------- +form_for [:admin, @article] +------- +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: + +------- +form_for [:admin, :management, @article] +------- +For more information on Rails' routing system and the associated conventions, please see the link:../routing_outside_in.html[routing guide]. + Making select boxes with ease ----------------------------- @@ -286,7 +328,7 @@ Here is what our wanted markup might look like: </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. +Here you have a list of cities where their names are presented to the user, but internally the application only wants to handle their IDs so they are used as the options' value attributes. Let's see how Rails can help out here. The select tag and options ~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -297,7 +339,7 @@ The most generic helper is `select_tag`, which -- as the name implies -- simply <%= 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: +This is a start, but it doesn't dynamically create our option tags. You can generate option tags with the `options_for_select` helper: ---------------------------------------------------------------------------- <%= options_for_select([['Lisabon', 1], ['Madrid', 2], ...]) %> @@ -309,7 +351,7 @@ output: ... ---------------------------------------------------------------------------- -For input data we used a nested array where each item has two elements: option text (city name) and option value (city id). +For input data you use a nested array where each element has two elements: option text (city name) and option value (city id). The option value is what will get submitted to your controller. It is often true that the option value 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: @@ -317,10 +359,10 @@ Knowing this, you can combine `select_tag` and `options_for_select` to achieve t <%= 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: +Sometimes, depending on an application's needs, you 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) %> +<%= options_for_select([['Lisabon', 1], ['Madrid', 2], ...], 2) %> output: @@ -331,12 +373,18 @@ output: 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 helpers for dealing with models -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +[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. +Until now you've seen 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 you 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: +Consistent with other form helpers, when dealing with models you drop the `_tag` suffix from `select_tag`. ---------------------------------------------------------------------------- # controller: @@ -346,49 +394,57 @@ Consistent with other form helpers, when dealing with models we drop the `"_tag" <%= 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. +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. -As before, if we were to use `select` helper on a form builder scoped to `@person` object, the syntax would be: +As before, if you 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, ...) %> ---------------------------------------------------------------------------- +[WARNING] +============================= +If you are using `select` (or similar helpers such as `collection_select`, `select_tag`) to set a `belongs_to` association you must pass the name of the foreign key (in the example above `city_id`), not the name of association itself. If you specify `city` instead of `city_id Active Record will raise an error along the lines of +-------- +ActiveRecord::AssociationTypeMismatch: City(#17815740) expected, got Fixnum(#1138750) +-------- +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. +============================ 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: +Until now you 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: +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: ---------------------------------------------------------------------------- <% 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: +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: ---------------------------------------------------------------------------- <%= 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`: +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`. 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`. +To recap, `options_from_collection_for_select` is to `collection_select` what `options_for_select` is 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: +To leverage time zone support in Rails, you 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 you can simply use the `time_zone_select` helper that already wraps this: ---------------------------------------------------------------------------- <%= time_zone_select(:person, :city_id) %> @@ -396,49 +452,293 @@ To leverage time zone support in Rails, we have to ask our users what time zone 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 +Rails _used_ to have a `country_select` helper for choosing countries but this has been extracted to the http://github.com/rails/country_select/tree/master[country_select plugin]. When using this do 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) + +Date and time select boxes +-------------------------- + +The date and time helpers differ from all the other form helpers in two important respects: + +1. Unlike other attributes you might typically have, dates and times are not representable by a single input element. Instead you have several, one for each component (year, month, day etc...). So in particular, there is no single value in your params hash with your date or time. +2. 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 + +Both of these families of helpers will create a series of select boxes for the different components (year, month, day etc...). +Barebones helpers +~~~~~~~~~~~~~~~~~ +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 -Miscellaneous +----------- +<%= select_date Date::today, :prefix => :start_date %> +----------- +outputs (with the actual option values omitted for brevity) +----------- +<select id="start_date_year" name="start_date[year]"> ... </select> +<select id="start_date_month" name="start_date[month]"> ... </select> +<select id="start_date_day" name="start_date[day]"> ... </select> +----------- +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 +----------- +Date::civil(params[:start_date][:year].to_i, params[:start_date][:month].to_i, params[:start_date][:day].to_i) +----------- +The :prefix option controls where in the params hash the date components will be placed. Here it was set to `start_date`, if omitted it will default to `date`. + +Model object helpers +~~~~~~~~~~~~~~~~~~~~ +`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. +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 +--------------- +<%= date_select :person, :birth_date %> +--------------- +outputs (with the actual option values omitted for brevity) +-------------- +<select id="person_birth_date_1i" name="person[birth_date(1i)]"> ... </select> +<select id="person_birth_date_2i" name="person[birth_date(2i)]"> ... </select> +<select id="person_birth_date_3i" name="person[birth_date(3i)]"> ... </select> +-------------- +which results in a params hash like +-------------- +{:person => {'birth_date(1i)' => '2008', 'birth_date(2i)' => '11', 'birth_date(3i)' => '22'}} +-------------- + +When this is passed to `Person.new`, 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`. + +Common options +~~~~~~~~~~~~~~ +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 http://api.rubyonrails.org/classes/ActionView/Helpers/DateHelper.html[API documentation]. + +As a rule of thumb you should be using `date_select` when working with model objects and `select_date` in others cases, such as a search form which filters results by date. + +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. + +Form builders ------------- -File upload form -~~~~~~~~~~~~~~~~ +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 a 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 + +---------- +<% form_for @person do |f| %> + <%= text_field_with_label f, :first_name %> +<% end %> +---------- +can be replaced with +---------- +<% form_for @person, :builder => LabellingFormBuilder do |f| %> + <%= f.text_field :first_name %> +<% end %> +---------- +by defining a LabellingFormBuilder class similar to the following: + +[source, ruby] +------- +class LabellingFormBuilder < FormBuilder + def text_field attribute, options={} + label(attribute) + text_field(attribute, options) + end +end +------- +If you reuse this frequently you could define a `labeled_form_for` helper that automatically applies the `:builder => LabellingFormBuilder` option. -:multipart - If set to true, the enctype is set to "multipart/form-data". +The form builder used also determines what happens when you do +------ +<%= render :partial => f %> +------ +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. 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: +`fields_for` creates a form builder in exactly the same way as `form_for` but doesn't create the actual `<form>` tags. It creates a scope around a specific model object like `form_for`, which is useful for specifying additional model objects in the same form. For example if you had a Person model with an associated ContactDetail model you could create a form for editing both like so: +------------- +<% form_for @person do |person_form| %> + <%= person_form.text_field :name %> + <% fields_for @person.contact_detail do |contact_details_form| %> + <%= contact_details_form.text_field :phone_number %> + <% end %> +<% end %> +------------- -Making custom form builders -~~~~~~~~~~~~~~~~~~~~~~~~~~~ +which produces the following output: -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 action="/people/1" class="edit_person" id="edit_person_1" method="post"> + <input id="person_name" name="person[name]" size="30" type="text" /> + <input id="contact_detail_phone_number" name="contact_detail[phone_number]" size="30" type="text" /> +</form> +------------- ----------------------------------------------------------------------------- -<% 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? %> +File Uploads +-------------- +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. + +The following two forms both upload a file. +----------- +<% form_tag({:action => :upload}, :multipart => true) do %> + <%= file_field_tag 'picture' %> <% end %> ----------------------------------------------------------------------------- +<% form_for @person, :html => {:multipart => true} do |f| %> + <%= f.file_field :picture %> +<% end %> +----------- +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]`. + +What gets uploaded +~~~~~~~~~~~~~~~~~~ +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). + +[source, ruby] +----------------- +def upload + uploaded_io = params[:person][:picture] + File.open(Rails.root.join('public', 'uploads', uploaded_io.original_filename), 'w') do |file| + file.write(uploaded_io.read) + end +end +---------------- -* `form_for` within a namespace +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 http://github.com/technoweenie/attachment_fu[Attachment-Fu] and http://www.thoughtbot.com/projects/paperclip[Paperclip]. ----------------------------------------------------------------------------- -select_tag(name, option_tags = nil, html_options = { :multiple, :disabled }) +NOTE: If the user has not selected a file the corresponding parameter will be an empty string. -select(object, method, choices, options = {}, html_options = {}) -options_for_select(container, selected = nil) +Dealing with Ajax +~~~~~~~~~~~~~~~~~ +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. -collection_select(object, method, collection, value_method, text_method, options = {}, html_options = {}) -options_from_collection_for_select(collection, value_method, text_method, selected = nil) +Parameter Names +--------------- +[[parameter_names]] +As you've seen in the previous sections values from forms can appear either at the top level of the params hash or may appear nested in another hash. For example in a standard create +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. -time_zone_options_for_select(selected = nil, priority_zones = nil, model = ::ActiveSupport::TimeZone) -time_zone_select(object, method, priority_zones = nil, options = {}, html_options = {}) ----------------------------------------------------------------------------- +Fundamentally HTML forms don't know about any sort of structured data. All they know about is name-value pairs. Rails tacks some conventions onto parameter names which it uses to express some structure. + +[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 + +------------- +ActionController::RequestParser.parse_query_parameters "name=fred&phone=0123456789" +#=> {"name"=>"fred", "phone"=>"0123456789"} +------------- +======================== + +Basic structures +~~~~~~~~~~~~~~~ +The two basic structures are arrays and hashes. Hashes mirror the syntax used for accessing the value in the params. For example if a form contains +----------------- +<input id="person_name" name="person[name]" type="text" value="Henry"/> +----------------- +the params hash will contain + +[source, ruby] +----------------- +{'person' => {'name' => 'Henry'}} +----------------- +and `params["name"]` will retrieve the submitted value in the controller. + +Hashes can be nested as many levels as required, for example +------------------ +<input id="person_address_city" name="person[address][city]" type="text" value="New York"/> +------------------ +will result in the params hash being + +[source, ruby] +----------------- +{'person' => {'address' => {'city' => 'New York'}}} +----------------- + +Normally Rails ignores duplicate parameter names. If the parameter name contains [] then they will be accumulated in an array. If you wanted people to be able to input multiple phone numbers, your could place this in the form: +----------------- +<input name="person[phone_number][]" type="text"/> +<input name="person[phone_number][]" type="text"/> +<input name="person[phone_number][]" type="text"/> +----------------- +This would result in `params[:person][:phone_number]` being an array. + +Combining them +~~~~~~~~~~~~~~ +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 +----------------- +<input name="addresses[][line1]" type="text"/> +<input name="addresses[][line2]" type="text"/> +<input name="addresses[][city]" type="text"/> +----------------- +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 a input name that already exists in the current hash. + +The one restriction is that although hashes can be nested arbitrarily deep then can be only one level of "arrayness". Frequently 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. + +[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. If the checkbox 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 hash. It is preferable to either use `check_box_tag` or to use hashes instead of arrays. + +Using form helpers +~~~~~~~~~~~~~~~~~ +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`/`fields_for` and the `:index` option. + +You might want to render a form with a set of edit fields for each of a person's addresses. Something a little like this will do the trick + +-------- +<% form_for @person do |person_form| %> + <%= person_form.text_field :name%> + <% for address in @person.addresses %> + <% person_form.fields_for address, :index => address do |address_form|%> + <%= address_form.text_field :city %> + <% end %> + <% end %> +<% end %> +-------- +Assuming our person had two addresses, with ids 23 and 45 this would create output similar to this: +-------- +<form action="/people/1" class="edit_person" id="edit_person_1" method="post"> + <input id="person_name" name="person[name]" size="30" type="text" /> + <input id="person_address_23_city" name="person[address][23][city]" size="30" type="text" /> + <input id="person_address_45_city" name="person[address][45][city]" size="30" type="text" /> +</form> +-------- +This will result in a params hash that looks like + +[source, ruby] +-------- +{'person' => {'name' => 'Bob', 'address' => { '23' => {'city' => 'Paris'}, '45' => {'city' => 'London'} }}} +-------- + +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 it is then easy to locate which Address record should be modified but you could pass numbers with some other significance, strings or even nil (which will result in an array parameter being created). + +To create more intricate nestings, you can specify the first part of the input name (`person[address]` in the previous example) explicitly, for example +-------- +<% fields_for 'person[address][primary]', address, :index => address do |address_form| %> + <%= address_form.text_field :city %> +<% end %> +-------- +will create inputs like +-------- +<input id="person_address_primary_1_city" name="person[address][primary][1][city]" size="30" type="text" value="bologna" /> +-------- +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 usually it is less repetitive to specify this at the form builder level rather than on individual input controls. + +As a shortcut you can append [] to the name and omit the `:index` option. This is the same as specifing `:index => address` so +-------- +<% fields_for 'person[address][primary][]', address do |address_form| %> + <%= address_form.text_field :city %> +<% end %> +-------- +produces exactly the same output as the previous example. + +Complex forms +------------- + +Many apps grow beyond simple forms editing a single object. For example when creating a Person instance 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: + +* Ryan Bates' series of railscasts on http://railscasts.com/episodes/75[complex forms] +* Handle Multiple Models in One Form from http://media.pragprog.com/titles/fr_arr/multiple_models_one_form.pdf[Advanced Rails Recipes] +* Eloy Duran's http://github.com/alloy/complex-form-examples/tree/alloy-nested_params[nested_params] plugin +* Lance Ivy's http://github.com/cainlevy/nested_assignment/tree/master[nested_assignment] plugin and http://github.com/cainlevy/complex-form-examples/tree/cainlevy[sample application] +* James Golick's http://github.com/giraffesoft/attribute_fu/tree[attribute_fu] plugin + +== Changelog == + +http://rails.lighthouseapp.com/projects/16213-rails-guides/tickets/1[Lighthouse ticket] + +.Authors +* Mislav Marohnić <mislav.marohnic@gmail.com> +* link:../authors.html#fcheung[Frederick Cheung] |