Forms

Ahmed A.
3 min readSep 24, 2020

--

While writing a web application, you may need to create or edit some data in the database. When in that situation you need to fill out a form to send the needed information to the database. In these situations you need to insert information into a form and send it to the database. We will be talking about three types of forms you can use, to create the form you see below.

form to create new user

Form types:

  • form_tag
  • form_for
  • form_with

form_tag

form_tag is usually used as a basic form, also with forms that are not used with specific controller actions. A good example of this type of form would be a contact or search form. This type of form is passed manually to the route and then the parameters are taken in. When a form_tag is filled out the form does not know where to go until we specifically tell it where to send the users submissions.

form using form_tag

form_for

form_for is an advanced version of form_tag. This works by taking values from your model and then attempts to find the correct route that is needed. As opposed to form_tag which needs to be told which route to take and will not attempt to find the correct route. This will lead to cleaner looking code and allow you to use a form variable and pass it to the block. These types of forms are best with model-forms, and use for database interaction. As you see below how the form_for is easier to read than the form_tag above.

form using form_for

form_with

According to Ruby on Rails documentation, it is noted that form_for and form_tag are unified into form_with. A benefit of using form_with is the ability to generate form tags based on URLs or models. When using, form_with with, URLs we pass a specific URL in the user_path area to submit the form. When using form_with with a model you pass a model object in the area like the from_for form . When using models with from_with we can use it for both new and preexisting records. A nice thing with using form_with with an existing record is that the input values will be filled out already.

form_with using URL
form_with using a Model

Conclusion

Forms are very useful for writing and editing data in the database. While any of these types of forms will work some require more work than others. form_with is the most useful because it can be used for any type of form that you will need for your web application. There are more options with form_with to customize it to your needs and you can further read the documentation to see those options.

--

--