Ruby on Rails Form Helpers Helpers for form elements



<%= 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") %>

This will generate the following html

<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

<%= radio_button_tag(:age, "child") %>
<%= label_tag(:age_child, "I am younger than 18") %>
<%= radio_button_tag(:age, "adult") %>
<%= label_tag(:age_adult, "I'm over 18") %>

This generates the following HTML

<input id="age_child" name="age" type="radio" value="child" />
<label for="age_child">I am younger than 18</label>
<input id="age_adult" name="age" type="radio" value="adult" />
<label for="age_adult">I'm over 18</label>

Text Area

To create a larger text box, it is recommended to use the text_area_tag

<%= text_area_tag(:message, "This is a longer text field", size: "25x6") %>

This will create the following HTML

<textarea id="message" name="message" cols="25" rows="6">This is a longer text field</textarea>

Number Field

This will create an input<type="number"> element

<%= number_field :product, :rating %>

To specify a range of values, we can use the in: option

<%= number_field :product, :rating, in: 1..10 %>

Password Field

Sometimes you want the characters typed by the user to be masked. This will generate an <input type="password">

<%= password_field_tag(:password) %>

Email Field

This will create an <input type="email">

<%= email_field(:user, :email) %>

Telephone Field

This will create an <input type="tel">.

<%= telephone_field :user, :phone %>

Date Helpers

  • input[type="date"]

    <%= date_field(:user, :reservation) %>
  • input[type="week"]

     <%= week_field(:user, :reservation) %>
  • input[type="year"]

     <%= year_field(:user, :reservation) %>
  • input[type="time"]

     <%= time_field(:user, :check_in) %>