PullMonkey Blog

11 Aug

Dynamic Select Boxes - Ruby on Rails 3

Over 4 years ago, I wrote a tutorial for doing dynamic (cascading) select boxes.
Still getting comments and emails to this day. Mostly asking how to get this working with rails 3, which has moved from prototype to jquery.
So here's a tutorial for getting 3 select boxes to trigger updates for each other.

First set things up:

I just used the html5 haml twitter bootstrap, etc template. Really useful.

If you need data, here's what I used - put this in your db/seeds.rb file:

Next, setup your model associations:

Genres have many artists.
Artists have many songs.
Genres have many songs through artists.

I'm just using a home controller to setup variables for the index page as well as setup variables for use in the dynamic updating:

Now the view just has the 3 select boxes and the unobtrusive javascript (triggered onchange) to make the ajax calls for updating:

We need our rjs files for updating the select boxes, one for the songs (when artist changes) and one for the artists and songs (when genre changes):

Our routes are simple:

That's it.

UPDATE: Here's an erb alternative for index.html.

And the js.haml can be converted to js.erb by taking #{...} and converting to <%= ... %> :