How to Use jQuery For Rails 3

jQuery is the de facto Javascript framework used by happy programmers. I am very glad to use it in almost all of the applications I am working on.

There are many posts on how to use it for Rails 3. But here’s another one which may help Rails 3 newbies (aren’t we all newbies when it comes to Rails 3?).

The jQuery Rails gem

In your Gemfile, include the jquery-rails gem created by Andre Arko of Engine Yard.

gem "jquery-rails"

And install the gem using the command:

bundle install

Install jQuery. The following command will remove prototype and scriptaculous files and add jQuery to your application:

rails generate jquery:install
or
rails g jquery:install

Using livequery

So you probably know that the following code will no longer work:

= link_to_remote 'delete', :url => admin_image_path(image), :confirm => 'Are you sure you want to delete this image?', :method => :delete 

They probably realized there’s way too much javascript on the body tags making Rails apps look ugly when you view the source.


// On application.js 

$('a[data-remote=true]').live('click', function() {
    $.ajax({ 
      url: this.href, 
      dataType: "script"
    }); 
    return false; 
});
 

$(function() {
  $(".alert").click(function() {
    alert(this.getAttribute("data-confirm"));
    return false;
  })
})

Replace the link_to_remote code with the following:

= link_to "Delete", admin_image_path(image), method: delete, confirm: "Are you sure you want to delete this image?",  remote: :true,  class: "alert"

That is it! Advantages of this code over the previous code is obvious. It’s not obtrusive and it works. Congratulations to all of us. We’re no longer living in caves and eating whatever exists in the wild. We actually have a choice.

Update:

For apps using Rails 3.1 and above, you do not need to include jquery-rails as it should already be included on the Gemfile. This post was written for Rails 3.0 users.

Please check the following project on github and read the documentation on jquery UJS. Adding suggested code on application.js is no longer necessary for current versions.