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.
Allows the user to input their email address. Returns a text_field of type “email”.
Let’s see how our webpage looks.
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.
Let’s take a look at our webpage.
Beautiful! The user cannot sign up a person who has not been born yet.
Returns an input tag of the “password” type.
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.
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.
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.
:doctor_id is a method of the object class (Appointment in this case).
@doctors is an array of all the Doctor objects. Each instance of a Doctor will create a HTML option tag.
:id will be assigned to each option tag created. This will be called on each object in the collection.
: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!