Labels

Rails supports a common feature of HTML that makes forms feel much more professional: labels. When labels are explicitly connected to the fields, clicking on the label shifts focus to the field. It gives users a bigger target to hit and simplifies accessibility as well.

Labels are easy. To make the headline “Name” associate with the field right below it, the scaffolding code uses:

<p>
    <%= f.label :name %><br />
    <%= f.text_field :name %>
  </p>

The generated HTML contains a bit of extra information the browser uses to make the association:

<p>
    <b><label for="person_name">Name</label></b><br />
    <input id="person_name" name="person[name]" size="30" type="text" />
  </p>

If you click on the word “Name,” focus will shift to the field for entering a name just below it.

If you want the label to say something other than the name of the field, just add a string as the second argument, as in:

<%= f.label :name, 'Your name' %>

This will generate:

<b><label for="person_name">Your name</label></b><br />

The label method is a nice feature, but at the same time it seems as if there’s a good deal of repetition going on in this code.

Get Learning Rails: Live Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.