rails 3 – PullMonkey Blog http://pullmonkey.com Thu, 16 Aug 2012 23:40:41 +0000 en-US hourly 1 https://wordpress.org/?v=5.6 Dynamic Select Boxes – Ruby on Rails 3 http://pullmonkey.com/2012/08/11/dynamic-select-boxes-ruby-on-rails-3/ http://pullmonkey.com/2012/08/11/dynamic-select-boxes-ruby-on-rails-3/#comments Sat, 11 Aug 2012 01:11:51 +0000 http://pullmonkey.com/?p=57726 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 <%= ... %> :

]]>
http://pullmonkey.com/2012/08/11/dynamic-select-boxes-ruby-on-rails-3/feed/ 12