Two Patterns for StimulusReflex Form Submissions
NOTE: for an updated version of this post, see my course StimulusReflex patterns, the forms lesson is included in the free samples! Forms are the standard CRUD pattern and can be handled by standard Rails remote forms perfectly. Still there might be times when you want to use your newly acquired StimulusReflex superpowers for a slicker user experience. My suggestion would be to stick to your last, but below are two patterns you can utilize to improve not only your user interactions, but also your application structure. 1. Vanilla CableReady On the StimulusReflex discord we frequently get asked how to best handle form submissions in reflexes. My answer tends to be: “Don’t”. Instead I’m first going to show you a more robust technique that relies on standard Rails remote forms and the power of CableReady. I’m borrowing a bit of the excellent Calendar Demo on StimulusReflex’s expo site for the purposes of this walkthrough. (If you want to follow along, this RailsByte will install StimulusReflex and TailwindCSS. You can also use the demo repo, complete with version tags) For starters, our tiny calendar app needs just one model, CalendarEvent, which we generate with a scaffold command: rails new calendula --template "https://www.railsbytes.com/script/z0gsd8" --skip-spring --skip-action-text --skip-active-storage --skip-action-mailer --skip-action-mailbox --skip-sprockets --skip-webpack-install bin/rails g scaffold CalendarEvent occurs_at:datetime description:text color:string In the index template, we only render two partials: One containing the form to add a new event, and the calendar grid itself. We inject @dates, which is just a collection of Date objects we want to display, and @calendar_events, all CalendarEvent s in this date range. <!-- app/views/calendar_events/index.html.erb --> <div id="calendar-form"> <%= render "form", calendar_event: @calendar_event %> </div>
Minthesize Company Blog