From d9412979002bdf0a30212880a2c595aa79d2539a Mon Sep 17 00:00:00 2001 From: Pratik Naik Date: Sat, 24 Jan 2009 15:39:48 +0000 Subject: Regenerate guides --- railties/doc/guides/html/form_helpers.html | 106 +++++++++++++++-------------- 1 file changed, 56 insertions(+), 50 deletions(-) (limited to 'railties/doc/guides') diff --git a/railties/doc/guides/html/form_helpers.html b/railties/doc/guides/html/form_helpers.html index 978beb4223..91b7b02574 100644 --- a/railties/doc/guides/html/form_helpers.html +++ b/railties/doc/guides/html/form_helpers.html @@ -34,7 +34,7 @@ Dealing With Basic Forms
  • @@ -173,7 +175,7 @@ Find out where to look for complex forms 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):

    +

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

    Sample output from form_tag
    @@ -184,7 +186,7 @@ Find out where to look for complex forms Form contents </form>
    -

    If you carefully observe this output, you can see that the helper generated something you didn’t specify: a div element with a hidden input inside. This is a security feature of Rails called cross-site request forgery protection and form helpers generate it for every form whose action is not "get" (provided that this security feature is enabled).

    +

    If you carefully observe this output, you can see that the helper generated something you didn’t specify: a div element with a hidden input inside. This is a security feature of Rails called cross-site request forgery protection and form helpers generate it for every form whose action is not "get" (provided that this security feature is enabled). You can read more about this in the Ruby On Rails Security Guide.

    @@ -193,7 +195,7 @@ Find out where to look for complex forms Throughout this guide, this div with the hidden input will be stripped away to have clearer code samples.
    -

    1.1. Generic search form

    +

    1.1. A 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. @@ -374,7 +376,7 @@ output:

      2. Dealing With Model Objects

      2.1. Model object helpers

      -

      A particularly common task for a form is editing or creating a model object. While the *_tag helpers could certainly be used for this task they are somewhat verbose as for each tag you would have to ensure the correct parameter name is used and set the default value of the input appropriately. Rails provides helpers tailored to this task. These helpers lack the _tag suffix, for example text_field, text_area.

      +

      A particularly common task for a form is editing or creating a model object. While the *_tag helpers can certainly be used for this task they are somewhat verbose as for each tag you would have to ensure the correct parameter name is used and set the default value of the input appropriately. Rails provides helpers tailored to this task. These helpers lack the _tag suffix, for example text_field, text_area.

      For these helpers the first argument is the name of an instance variable and the second is the name of a method (usually an attribute) to call on that object. Rails will set the value of the input control to the return value of that method for the object and set an appropriate input name. If your controller has defined @person and that person’s name is Henry then a form containing:

      @@ -385,7 +387,7 @@ output:
      <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.

      +

      Upon form submission the value entered by the user will be stored in params[:person][:name]. The params[:person] hash is suitable for passing to Person.new or, if @person is an instance of Person, @person.update_attributes. While the name of an attribute is the most common second parameter to these helpers this is not compulsory. In the example above, as long as person objects have a name and a name= method Rails will be happy.

      @@ -449,7 +451,7 @@ Methods to create form controls are called on the form builder <input name="commit" type="submit" value="Create" /> </form> -

      The name passed to form_for controls the key used in params for form’s values. 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 section.

      +

      The name passed to form_for controls the key used in params to access the form’s values. Here the name is article and so all the inputs have names of the form article[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 section.

      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.

      You can create a similar binding without actually creating <form> tags with the fields_for helper. This is useful for editing additional model objects with the same form. For example if you had a Person model with an associated ContactDetail model you could create a form for editing both like so:

      @@ -471,7 +473,7 @@ Methods to create form controls are called on the form builder

      The object yielded by fields_for is a form builder like the one yielded by form_for (in fact form_for calls fields_for internally).

      2.3. Relying on record identification

      -

      The Article model is directly available to users of our application, so — following the best practices for developing with Rails — you should declare it a resource.

      +

      The Article model is directly available to users of the application, so — following the best practices for developing with Rails — you should declare it a resource.

      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:

      @@ -488,7 +490,7 @@ form_for(:article, @article, :url => article_path(@article), :method => "p 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?. 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.

      +

      Rails will also automatically set the class and id of the form appropriately: a form creating an article would have id and class new_article. If you were editing the article with id 23 the class would be set to edit_article and the id to edit_article_23. These attributes will be omitted for brevity in the rest of this guide.

      @@ -510,7 +512,7 @@ form_for(@article)

      For more information on Rails' routing system and the associated conventions, please see the routing guide.

      2.4. 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 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.

      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:

      @@ -525,7 +527,7 @@ output: </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).

      +

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

      3. Making select boxes with ease

      @@ -534,7 +536,7 @@ output:
      <select name="city_id" id="city_id">
      -  <option value="1">Lisabon</option>
      +  <option value="1">Lisbon</option>
         <option value="2">Madrid</option>
         ...
         <option value="12">Berlin</option>
      @@ -545,26 +547,26 @@ output:
       

      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>...') %>
      +
      <%= select_tag(:city_id, '<option value="1">Lisbon</option>...') %>
      -

      This is a start, but it doesn’t dynamically create our option tags. You can generate option tags with the options_for_select helper:

      +

      This is a start, but it doesn’t dynamically create the option tags. You can generate option tags with the options_for_select helper:

      -
      <%= options_for_select([['Lisabon', 1], ['Madrid', 2], ...]) %>
      +
      <%= options_for_select([['Lisbon', 1], ['Madrid', 2], ...]) %>
       
       output:
       
      -<option value="1">Lisabon</option>
      +<option value="1">Lisbon</option>
       <option value="2">Madrid</option>
       ...
      -

      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.

      +

      The first argument to options_for_select is a nested array where each element has two elements: option text (city name) and option value (city id). The option value is what will be submitted to your controller. Often this will be the id of a corresponding database object but this does not have to be the case.

      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 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 allows you to pre-select an option by specify its value as the second argument:

      <%= options_for_select([['Lisabon', 1], ['Madrid', 2], ...], 2) %>
      @@ -575,20 +577,19 @@ output:
       <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.

      +

      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.

      +

      The second argument to options_for_select must be exactly equal to the desired internal value. In particular if the value is the integer 2 you cannot pass "2" to options_for_select — you must pass 2. Be aware of values extracted from the params hash as they are all strings.

      3.2. Select boxes for dealing with models

      -

      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 you drop the _tag suffix from select_tag.

      +

      In most cases form controls will be tied to a specific database model and as you might expect Rails provides helpers tailored for that purpose. Consistent with other form helpers, when dealing with models you drop the _tag suffix from select_tag:

      # controller:
      @@ -598,7 +599,7 @@ output:
       <%= select(:person, :city_id, [['Lisabon', 1], ['Madrid', 2], ...]) %>

      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 you were to use select helper on a form builder scoped to @person object, the syntax would be:

      +

      As with other helpers, if you were to use select helper on a form builder scoped to @person object, the syntax would be:

      # select on a form builder
      @@ -610,22 +611,18 @@ output:
       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

      +

      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)
      +
      ActiveRecord::AssociationTypeMismatch: City(#17815740) expected, got String(#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.

      3.3. Option tags from a collection of arbitrary objects

      -

      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 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:

      +

      Generating options tags with options_for_select requires that you create an array containing the text and value for each option. But what if you had a City model (perhaps an Active Record one) and you wanted to generate option tags from a collection of those objects? One solution would be to make a nested array by iterating over them:

      <% cities_array = City.find(:all).map { |city| [city.name, city.id] } %>
      @@ -636,17 +633,17 @@ output:
       
      <%= options_from_collection_for_select(City.all, :id, :name) %>
      -

      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:

      +

      As the name implies, this only generates option tags. To generate a working select box you would need to use it in conjunction with select_tag, just as you would with options_for_select. When working with model objects, just as select combines select_tag and options_for_select, collection_select combines select_tag with options_from_collection_for_select.

      <%= collection_select(:person, :city_id, City.all, :id, :name) %>

      To recap, options_from_collection_for_select is to collection_select what options_for_select is to select.

      3.4. Time zone and country select

      -

      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:

      +

      To leverage time zone support in Rails, you have to ask your users what time zone they are in. Doing so would require generating select options from a list of pre-defined TimeZone objects using collection_select, but you can simply use the time_zone_select helper that already wraps this:

      -
      <%= time_zone_select(:person, :city_id) %>
      +
      <%= time_zone_select(:person, :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.

      Rails used to have a country_select helper for choosing countries but this has been extracted to the 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).

      @@ -657,12 +654,12 @@ output:
      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. +Dates and times are not representable by a single input element. Instead you have several, one for each component (year, month, day etc.) and so there is no single value in your params hash with your date or time.

      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 +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.

      @@ -673,27 +670,27 @@ Other helpers use the _tag suffix to indicate whether a helper is a barebones he
      <%= select_date Date::today, :prefix => :start_date %>
      -

      outputs (with the actual option values omitted for brevity)

      +

      outputs (with 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

      +

      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.

      +

      The :prefix option is the key used to retrieve the hash of date components from the params hash. Here it was set to start_date, if omitted it will default to date.

      4.2. 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

      +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)

      +

      outputs (with actual option values omitted for brevity)

      <select id="person_birth_date_1i" name="person[birth_date(1i)]"> ... </select>
      @@ -705,7 +702,7 @@ The model object helpers for dates and times submit parameters with special name
       
      {: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.

      +

      When this is passed to Person.new (or update_attributes), Active Record spots that these parameters should all be used to construct the birth_date attribute and uses the suffixed information to determine in which order it should pass these parameters to functions such as Date::civil.

      4.3. 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 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.

      @@ -717,6 +714,15 @@ The model object helpers for dates and times submit parameters with special name
      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.
      +

      4.4. Individual Components

      +

      Occasionally you need to display just a single date component such as a year or a month. Rails provides a series of helpers for this, one for each component select_year, select_month, select_day, select_hour, select_minute, select_second. These helpers are fairly straightforward. By default they will generate a input named after the time component (for example "year" for select_year, "month" for select_month etc.) although this can be override with the :field_name option. The :prefix option works in the same way that it does for select_date and select_time and has the same default value.

      +

      The first parameter specifies which value should be selected and can either be an instance of a Date, Time or DateTime, in which case the relevant component will be extracted, or a numerical value. For example

      +
      +
      +
      <%= select_year(2009) %>
      +<%= select_year(Time.now) %>
      +
      +

      Will produce the same output if the current year is 2009 and the value chosen by the user can be retrieved by params[:date][:year].

      5. Uploading Files

      @@ -856,18 +862,18 @@ http://www.gnu.org/software/src-highlite --> <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.

      +

      The one restriction is that although hashes can be nested arbitrarily deep then can be only one level of "arrayness". Arrays can be usually replaced by hashes, for example instead of having an array of model objects one can have a hash of model objects keyed by their id, an array index or some other parameter.

      - +
      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.Array parameters do not play well with the check_box helper. According to the HTML specification unchecked checkboxes submit no value. However it is often convenient for a checkbox to always submit a value. The check_box helper fakes this by creating a second hidden input with the same name. If the checkbox is unchecked only the hidden input is submitted and if it is checked then both are submitted but the value submitted by the checkbox takes precedence. When working with array parameters this duplicate submission will confuse Rails since duplicate input names are how it decides when to start a new array element. It is preferable to either use check_box_tag or to use hashes instead of arrays.

      7.3. 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

      +

      The previous sections did not use the Rails form helpers at all. While you can craft the input names yourself and pass them directly to helpers such as text_field_tag Rails also provides higher level support. The two tools at your disposal here are the name parameter to form_for and fields_for and the :index option that helpers take.

      +

      You might want to render a form with a set of edit fields for each of a person’s addresses. For example:

      <% form_for @person do |person_form| %>
      @@ -879,7 +885,7 @@ http://www.gnu.org/software/src-highlite -->
         <% end %>
       <% end %>
      -

      Assuming our person had two addresses, with ids 23 and 45 this would create output similar to this:

      +

      Assuming the 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">
      @@ -895,7 +901,7 @@ by Lorenzo Bettini
       http://www.lorenzobettini.it
       http://www.gnu.org/software/src-highlite -->
       
      {'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).

      +

      Rails knows that all these inputs should be part of the person hash because you called fields_for on the first form builder. By specifying an :index option you’re telling rails that instead of naming the inputs person[address][city] it should insert that index surrounded by [] between the address and the city. If you pass an Active Record object as we did then Rails will call to_param on it, which by default returns the database id. This is often useful as it is then easy to locate which Address record should be modified. You can pass numbers with some other significance, strings or even nil (which will result in an array parameter being created).

      To create more intricate nestings, you can specify the first part of the input name (person[address] in the previous example) explicitly, for example

      @@ -908,7 +914,7 @@ http://www.gnu.org/software/src-highlite -->
      <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 general rule the final input name is the concatenation of the name given to fields_for/form_for, the index value and the name of the attribute. You can also pass an :index option directly to helpers such as text_field, but it is usually less repetitive to specify this at the form builder level rather than on individual input controls.

      As a shortcut you can append [] to the name and omit the :index option. This is the same as specifing :index => address so

      @@ -920,7 +926,7 @@ http://www.gnu.org/software/src-highlite -->

      8. Building 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:

      +

      Many apps grow beyond simple forms editing a single object. For example when creating a Person you might want to allow the user to (on the same form) create multiple address records (home, work etc.). When later editing that person the user should be able to add, remove or amend addresses as necessary. While this guide has shown you all the pieces necessary to handle this, Rails does not yet have a standard end-to-end way of accomplishing this, but many have come up with viable approaches. These include:

      • -- cgit v1.2.3