Form Partials Refactoring New and Edit Forms Into a Single Form
In this demonstration, I will show how to refactor new and edit forms into a single form using a form partial.
General Steps
In general, the steps for refactoring the new and edit forms into a single form are as follows.
-
Step 1 Create the Form Partial. This step creates the form partial that will be the structure of the new and edit pages.
-
Step 2 Replace Previous Forms with Render Statement. This step replaces the new and edit forms with a statement that instructs the page to render the form partial.
Refactoring New and Edit Forms with a Form Partial in the Todo App
To demonstrate the steps for refactoring forms into form partial, we will be creating a form partial for the new and edit forms in the Todo App.
Step 1 Create the Form Partial
Substep
Create _form.html.erb. To create the form partial file, we place a new file called _form.html.erb
in the folder app/views/todos
. By convention, the name of any partial HTML files rendered on other pages begin with an underscore.
Substep
Rough in the Form. To begin the form, we copy/paste one of the existing forms in either new.html.erb
or edit.html.erb
. They should be the same except for the form header, which will change in the next step.
At the point our file looks like this:
<%= bootstrap_form_with model: @todo, url: todo_path(@todo), method: :patch, local: true do |f| %>
<%= f.text_field :title %>
<%= f.text_area :description %>
<%= f.date_field :due_date %>
<%= f.submit %>
<% end %>
Substep
Modify Form Header. To complete the form partial, we remove the url
and method
options from the form header. These will be inferred automatically by Rails based on the object passed through the model
option. If it does not have an ID, Rails will use the create route and action. Likewise, if the object has an ID, Rails will use the update route and action.
The completed form partial looks like this:
<%= bootstrap_form_with model: @todo, local: true do |f| %>
<%= f.text_field :title %>
<%= f.text_area :description %>
<%= f.date_field :due_date %>
<%= f.submit %>
<% end %>
Test It!
There is no way to confirm this yet. We will test it after the next step.
Step 2 Replace Previous Forms with Render Statement
To render the forms on new.html.erb
and edit.html.erb
, we use a render statement and pass the form partial into it, replacing the entire form like so:
<h1>Create New To-Do Item</h1>
<%= render "form" %>
<h1>Edit To-Do Item</h1>
<%= render "form" %>
Test It!
To confirm that we made this change correctly, we boot up the server then create and edit a to do item. If done correctly, the webapp will behave exactly as before.
Conclusion
Following the above steps, we have now extracted the new and edit forms in the ToDo app to a form partial.