form_for/form_with/form_tag

While learning ruby, i struggled greatly understanding and expelling forms. I couldn’t quite understand which form to use, and why should i select one over the other. Hopefully, you’ve landed here because you have the same problem and i can help clear up your confusion.

Form_tag

Before Rails 5.1, rails utilized and the . While both would create a form, ’s are utilized for forms that are connected to a custom url or a specific Controller action.

The syntax for is as follows

In the example above, on line 2, our is equal to the users path and since there are no options, we proceed with the syntax for forms. Please visit this link to review types of options available. The method for the form defaults to POST.

The reason you would want to use is if you do not have a model corresponding to the information being entered. The advantages would be a direct access to the path or route.

Form_for

is utilized when the form is connected with an Active Record model. allows us to create or update the attributes of a specific model object.

The syntax for is

In our example above, the record that we would like to update is and like the first example there are no options so we proceed. You can visit here to see what options are available.

The reason you would want to use is to “rely on Rails to infer automatically from the model.”

Form_with

is utilized as a generic form. After Rails 5.1, was added

The syntax for is

In the example above a url has been passed in. This tells the form where to make the request, but you can also pass ActiveRecord objects to the form using . It’s kinda like the best of both worlds rather than making the decision to use one or the other.

is much easier to use, but it is helpful to know the difference and what goes on under the hood. Understanding the difference can help you utilize to its best ability. will eventually replace form_with and form_for.

Thank you for reading!!!Hope you’ve learned something!