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 form_for
and the form_tag
. While both would create a form, form_tag
’s are utilized for forms that are connected to a custom url or a specific Controller action.
The syntax for form_tag
is as follows
form_tag(url_for_options = {}, options = {}, &block)public
In the example above, on line 2, our url_for_options
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 form_tag
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
form_for
is utilized when the form is connected with an Active Record model. form_for
allows us to create or update the attributes of a specific model object.
The syntax for form_for
is
form_for(record, options = {}, &block)
In our example above, the record that we would like to update is :person
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 form_for
is to “rely on Rails to infer automatically from the model.”
Form_with
form_with
is utilized as a generic form. After Rails 5.1, form_with
was added
The syntax for form_with
is
form_with(model:nil, scope:nil, url:nil, format:nil, **options)
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 model:
. It’s kinda like the best of both worlds rather than making the decision to use one or the other.
form_with
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 form_with
to its best ability. form_with
will eventually replace form_with and form_for.
Thank you for reading!!!Hope you’ve learned something!