Using form_with in Ruby on Rails

Nicholas Merolle
3 min readAug 7, 2021

While learning about the form_tag and form_for helper methods that are used in Ruby on Rails to create HTML forms I noticed that the rails guides only listed form_with. At the bottom of the page was a small footnote about both form_tag and form_for being soft deprecated. After a little searching I learned that with the release of Rails 5.1 on May 10th, 2017 a form_with helper method unified both the form_tag and form_for helper methods. I was still using lessons based on the now deprecated helper methods, I was a little shocked, even a little angry as to why these lessons were outdated by four years. After thinking for a moment I realized any code written in Rails prior to May 2017 would still be using the older helper methods and so it was worth learning them. I decided to begin my project using the older methods and later convert them to form_with helpers so I can along the way learn that as well, no lessons were provided on form_with, but the rails guides have plenty of info on it.

The form_tag helper is used whenever we want to create a form that does not require a model to create or edit anything, or in other words does not persist data to the database an example of this is user login. I will post a copy of my user login view from my sessions views using form_tag.

/app/views/sessions/new with form_tag

The form_tag accepts a url in this case login_path renders the login form. The same behavior (and HTML) is achieved using form_with as shown next.

/app/views/sessions/new with form_with

The form_with helper accepts the same url and produces the same exact form, note that the “scope: :user” after form_with creates a prefix of user for the inputs so f.email_field :email will actually get stored in params as user[:email] and the same for any other input including the password on the form.

Next lets take a look at the user signup view and see how this is built with form_for. The form_for helper is used whenever we have a model object that we are creating or updating information for in the database. As such we must have an actual model. Below is the format for a basic user signup form with name, e-mail and password attributes using form_for. Notice we know use an object instance in stead of a url in to feed to the form block.

/app/views/users/new with form_for

The form_with helper method works and pretty much looks exactly the same as shown below. Note that the parantheses I used on line are not required, I used them early on so as not to confuse myself, the form_with helper works withor without them.

/app/views/users/new with form_with

I hope this may make it easier for others who also want to avoid using soft deprecated helpers in their forms.

--

--