Rails form_with - alternative to form_for and form_tag
Rails 5.1 added form_with
form helper method
that provides capabilities of form_for
and form_tag
.
Rails unified form_for
and form_tag
that provide similar interfaces
to generate forms with form_with
helper.
form_for
was being used to generate form for a new/existing model object.form_tag
was used to create form without a model object by passing a URL to submit the form.
Before Rails 5.1
form_for
with model object
form_for
was used when we had to create a form for a model object.
This generates DOM shown below.
Behavior:
- We can see Rails automaitcally assigns
id
attribute value to thenew_user
if record is new. id
attribute is set toedit_user_<id>
, where<id>
is the primary key ofusers
table.- It fills out the input values if the model object is not new.
After Rails 5.1
form_with
with a model object
This generates DOM given below.
Behavior:
- Automatic IDs for the form are gone.
- The above way of creating form works for both new and existing records.
- It fills out the input values if the model object is not new.
Before Rails 5.1
form_tag
without model object
form_tag
was used when we had to create a form without any model object providing URL endpoint to submit the form.
Both helper methods used to create DOM of the form tag with necessary DOM content.
After Rails 5.1
form_with
without a model object
form_with
provides an option to pass a URL to be used for the submit action.
This generates DOM given below.
form_with
with a scope (prefix)
Now, we can see that above code, does not prefix input fields as it does when generated with model object.
To generate input fields with some prefix, Rails provides scope
option.
This generates DOM given below.
form_with
ajax submit events
As we can see form_with
adds data-remote
attribute with value set to true
.
This makes sure that form is submitted with AJAX if unobtrusive javascript driver
like rails-ujs
is used.
If your application uses rails-ujs
, the form will be submitted via ajax,
and it listens on following events.
ajax:success
: This event is called when Ajax response is success.ajax:error
: This event is called when Ajax response is failure.
Event can be binded on form as given below.
Subscribe to Ruby in Rails
Get the latest posts delivered right to your inbox