constraint-validation-example

Expand History Expand History
Collapse History Collapse History

Store invalid submission parameters in the Flash

New Dependencies

First, add the turbo gem and a dev-build of the basecamp/turbolinks release of Turbolinks 6 alpha.

Next, remove @rails/ujs from the package.json and remove the import and call to Rails.start(). Most of the value of Rails Unobtrusive JavaScript will be replaced by Turbolinks, either through the new turbolinks:submit-start and turbolinks:submit-end events or other existing turbolinks:-prefixed events.

Finally, add activerecord-session_store and use it to replace the cookie store.

Implementation details

Turbolinks 6 will require that every form submission response results in a redirect or a visit. This is incompatible with the popular Rails pattern of in-place HTML rendering with a call to render :new or render :edit (from a #create or #update action, respectively).

As an alternative to relying on a ActiveModel or ActiveRecord instance state, write the parameters submitted to the messages#create action to the (ActiveRecord::SessionStore-backed) Flash under the params: key.

This extension is scoped to the FlashParams controller concern.

Next, once redirected to the messages#index, read the parameters from flash[:params], and pass those to Message.restore_submission. Within Message.restore_submission, assign the attributes and call #validate so that the record is marked as invalid and the error messages are available for the form_with call in the messages#index template.

In cases where a visit to messages#index is not a result of a invalid form submission, but is instead a direct visit, skip the call to #validate.

This extension is scoped to the Restorable model concern.

ARIA attributes for invalid forms

To set a baseline for this example application’s Accessibility (a11y), ensure that the <input type="text"> element that captures the value for content declares an aria-describedby attribute that references a <span> element with a matching [id] attribute that renders the error message.