Form helpers… which one should I use?

Ruby on Rails has a series of form helpers that can be used for specific database records. We know about text_field for text input and number_field for numeric input. But we can do so much more!

These helpers have different uses for specific cases of user input. I’ll be reviewing a list of what I think are the most helpful helpers for form control. I am using form_for in the following examples.

email_field

Allows the user to input their email address. Returns a text_field of type “email”.

Let’s see how our webpage looks.

The user cannot proceed without a valid email address. Pretty cool, right?

date_field

Allows users to enter a date via calendar option or by typing a numeric value. Returns a text_field of type “date”. You can add “min” and “max” attributes to limit user input.

I’ve limited the user’s birthdate options between 01/01/1920 and today’s date.

Let’s take a look at our webpage.

Beautiful! The user cannot sign up a person who has not been born yet.

password_field

Returns an input tag of the “password” type.

The user’s input is hidden

radio_button

radio_button allows for form control. It creates a radio button and gives users a set of options. The user can only select one button.

In this case, an appointment is created with one doctor

Let’s take a look at the code.

.radio_button takes in two arguments.

First, the method.
:doctor_id is an attribute of the Appointment class and a property of the object — Appointment.

Second, the value.
doctor.id assigns each option’s value to its id in the database. If you look at my code above, I am iterating through each doctor in my database and assigning each doctor’s id to the value.

But this doesn’t seem DRY enough though. Let’s refactor.

collection_radio_buttons

So DRY! Love it. If you are familiar with the collection_select form helper, you can see that it looks familiar. If you aren’t, that’s OK.

collection_radio_ buttons takes in 4 arguments.

First, method.
:doctor_id is a method of the object class (Appointment in this case).

Second, collection.
@doctors is an array of all the Doctor objects. Each instance of a Doctor will create a HTML option tag.

Third, value.
:id will be assigned to each option tag created. This will be called on each object in the collection.

Fourth, text.
:name is what will be displayed on the webpage. It will display your choice of attribute from the collection object.

As you can see, there are various types of form helpers available for different use cases, allowing us to control user input. I encourage you to check out the sources below for a more detailed overview or to learn about the many other helpers I did not discuss. Happy coding!

Software Engineer

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store