Sep 25 2010

How to Use jQuery For Rails 3

Rails3 jQuery | comments

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.

There's a need to include livequery within the head tag or before closing body tag if you wish to follow the YSlow recommendations.

              
              On application.js 
              
              $('a[data-remote=true]').livequery('click', function() {
                  $.ajax({ 
                    url: this.href, 
                    dataType: "script"
                  }); 
                  return false; 
              });
               
              
              $('form[data-remote=true]').livequery('submit', function() {
                return request({ url : this.action, type : this.method, data : $(this).serialize() });
              });
              
              $(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.