This is just a quicky, to help out anyone using Rails 6, or any Stimulus-enabled Rails project and Select2, the amazing jQuery plugin for better select boxes.
In a new project, I’m writing a Rails 6 app and using Stimulus. It’s an interesting challenge. I’ve been so neck-deep in Zonmaster — which is built on Rails 4(!!) — that I’ve not really been paying much attention to developments. BookMatchClub is a great opportunity to find out more.
Simple Select2 + Stimulus Controller
In BookMatchClub we do a lot of tagging and want authors to be able to filter things based on those tags. For this, I went with Select2. Using the basics with Stimulus was fairly easy.
This works fine if all you want to do is have a field in your form that supports tagging.
Acting on Events
But what I wanted to do was when the tag field was changed fire an Ajax request to get some data from the back end. i.e. a filter.
The issue is that Select2 does not use ‘native’ events. They have their own event framework. So what you need to do is capture the Select2 event and refire a native event. Simple, once you know that!
Here’s a quick example:
There are two key parts here.
First, catching the Select2 event in the controller. I chose to use the
select2:select
event because catching ‘change’ caused a loop.
The second thing is putting the action on the select field of the form:
<%= form.select :tags, ... 'data-action':'change->filter#updateToTagOptions' %>
This is the action that will get triggered when you fire the native event.
I hope that helps someone. I couldn’t find a single place with all this info together.
Talk to me!
You can find me on Twitter where I share insights on Ruby on Rails, discuss my journey with Zonmaster, and explore various aspects of life. You can also check out my YouTube channel where I cover various topics related to web development, including Ruby on Rails.
And guess what? I’ve recently released my first guide, “Getting Started with Ruby on Rails: A Step-by-Step Guide for Beginners” on Gumroad! 📚🚀 It’s a ‘Fair Price’ ebook, so you can get it for free, but any payment is greatly appreciated as it helps support my work and future guides. Don’t miss out on this opportunity to level up your web development skills with Rails!
Drop me a note on Twitter or LinkedIn if you have any questions or need help with your Rails project. Happy coding! 😊🎉