T S Vallender

Slim Select in Rails

Today I needed to add a searchable select box to a form in a Rails application. Select2 has historically been the go-to option for this, but it uses JQuery, which I’d like to avoid. Having heard good things about Slim Select, I thought I’d give it a go. Here’s a quick guide to add it to a Rails application.

Installation


I’m going to assume a standard modern Rails application here, so we’ll be using import maps. Run:
$ ./bin/importmap pin "slim-select"

Which will add a reference to Slim Select to your import maps and vendor the JavaScript.

We also need to grab the CSS or things are going to look very strange indeed. Unfortunately I don’t know of any nice way to do this programatically and keep it updated—I simply downloaded the CSS file and added it to my stylesheets directory.

Stimulus controller


Continuing down the route of keeping things vanilla Rails, I then set up a Stimulus controller to use whenever I want a Slim Select input. It’s as simple as:

import { Controller } from "@hotwired/stimulus"
import SlimSelect from "slim-select"

export default class extends Controller {
  connect() {
    new SlimSelect({
      select: this.element
    })
  }
}

And then simply connect any select input to this controller, for example:

<%= f.collection_select :foo_id, Foo.all, :id, :name, {}, { data: { controller: "slim-select" } } %>

Et voilà!

image.png 15.7 KB

Updated at 2024-05-10 15:59 | 2024-05-10 15:58