Auto Save Form Data in Rails
In this tutorial I’m going to show you how to automatically save form data in Rails. Instead of saving a draft to the database, we’ll simply leverage Stimulus JS to save the data to localStorage. Below is what we’ll be creating.
Step 1: Setup
Run the following commands to create a new Rails application. If you’re using an existing Rails application, make sure to install Stimulus by running rails webpacker:install:stimulus
.
rails new rails-auto-save-form-data -d=postgresql --webpacker=stimulus
rails db:create
rails db:migrate
rails g scaffold Post title body:text
rails db:migrate
Step 2: Create the Stimulus Controller
Next we’ll need to create a Stimulus Controller to store our Javascript.
-
touch app/javascript/controllers/auto_save_controller.js
-
Connect the Controller to the post form.
Step 3: Save Form Data to localStorage.
Next we’ll want to save the form data to localStorage
each time the form is updated.
-
Update
app/javascript/controllers/auto_save_controller.js
with the following code. -
Add
action: "change->auto-save#saveToLocalStorage"
to the post form.
Every time the form changes, the values are saved to localStorage
Step 4: Populate the Form with Data from localStorage
Now that we’re saving data into localStorage
we need to populate the form with those values.
- Update
app/javascript/controllers/auto_save_controller.js
with the following code.
Step 5: Clear localStorage when Form is Submitted
Finally, we’ll want to clear the form data from localStorage
once the form submits. Otherwise, old drafts will continue to be persisted in the form.
- Update
app/javascript/controllers/auto_save_controller.js
with the following code.
-
Add
action: "submit->auto-save#clearLocalStorage"
to the post form.
Security Considerations
I don’t recommend using this technique on forms that store sensitive data such as passwords or credit cards, since their values would be stored in plain text in localStorage
.