Generating Forms

Get familiar with the HTML forms using templates

We'll cover the following...

Gathering information using HTML form

HTML provides a number of elements, attributes, and attribute values that control how input is gathered. We could certainly hand-code our form directly into the template, but there is no need to do that.

In this chapter, we will cover a number of helpers that Rails provides to assist with this process.

HTML provides a number of ways to collect data in forms. A few of the more common means are shown below. Note that the form itself is not representative of any sort of typical use; in general, we’ll use only a subset of these methods to collect data.

A basic HTML form

Let’s look at the template that was used to produce that form:

Press + to interact
<%= form_for(:model) do |form| %>
<p>
<%= form.label :input %>
<%= form.text_field :input, :placeholder => 'Enter text here...' %>
</p>
<p>
<%= form.label :address, :style => 'float: left' %>
<%= form.text_area :address, :rows => 3, :cols => 40 %>
</p>
<p>
<%= form.label :color %>:
<%= form.radio_button :color, 'red' %>
<%= form.label :red %>
<%= form.radio_button :color, 'yellow' %>
<%= form.label :yellow %>
<%= form.radio_button :color, 'green' %>
<%= form.label :green %>
</p>
<p>
<%= form.label 'condiment' %>:
<%= form.check_box :ketchup %>
<%= form.label :ketchup %>
<%= form.check_box :mustard %>
<%= form.label :mustard %>
<%= form.check_box :mayonnaise %>
<%= form.label :mayonnaise %>
</p>
<p>
<%= form.label :priority %>:
<%= form.select :priority, (1..10) %>
</p>
<p>
<%= form.label :start %>:
<%= form.date_select :start %>
</p>
<p>
<%= form.label :alarm %>:
<%= form.time_select :alarm %>
</p>
<% end %>

In the above template, we’ll see a number of labels, like the one in line 3. We use labels to associate text with an input field for a specified ...