I've been looking for some information on the unobtrusive javascript features in Rails 3, and it turns out that there's not much out there! Either that, or I'm looking in the wrong places.

So here is my attempt to explain some of the features. I'll create two sample blog apps, one using Prototype and the other using JQuery (the code is available on github).

Install Rails 3

If you haven't already, get Rails 3 installed. Everything you need to know is here.

What is UJS?

In older versions of Rails there was a DSL called RJS. This basically allowed the user to write Javascript using Ruby. However, RJS was tightly coupled to the Prototype JS framework... so if you wanted to use JQuery or MooTools you would need to do make your own solution.

This preference for Prototype lead people to want a more loosely coupled approach, which didn't discriminate against other JS frameworks. Enter UJS...

How it works

Rails 3 makes use of HTML5 data-* tags to store pertinent data along with the element in question. This removes the need for inline javascript to be stored in the element, as it was with delete links in the past. The main player in this is data-remote="true", which is used to tell the form or link that it should perform an asynchronous request to the server.

Javascript Drivers

The above is achieved with some help from a javascript driver file that uses Prototype by default but can easily be changed to a JQuery driver. The file is called rails.js and is located in the "javascripts" folder. Here are some of the drivers available:-

To use another driver simply swap the rails.js with the one you want to use and include the appropriate javascript library.

Let's give it a go!

I'm not going to take you through the whole process of creating the Rails app. What I will show you is the parts that relate to UJS requests.

As I said this is a sample Blog app, so we have a Posts - Comments relationship set up. In the show.html.erb view we have a form for creating new comments:-


The main thing to notice about the form_for block is the :remote => true parameter. This will take care of the data-remote=true HTML5 attribute, that we discussed earlier. So when we submit this form it will send an ajax request to the "create" action in the comments controller:-


Notice that the controller responds to the :js format. So the controller will pass control to the create.js.erb view:-


This displays the new comment at the bottom of the list and highlights it, then finally it clears the form text area.

I've used the :remote => true option for deleting posts as well. Take a look at the demo code to see how this works. It's very similar to the example above.

That's pretty much it. Here's the prototype and jquery demos on github.