Tuesday, April 12, 2011

Enabling UJS in Rails3 with jQuery: in just 3 steps!

Here is my approach to quickly enabling Unobtrusive Javascript support for your Rails application, using jQuery:

  1. Create a Rails application without Prototype support
    $ rails new myCommentsApp --skip-prototype
    view raw gistfile1.sh hosted with ❤ by GitHub
  2. Edit your config/application.rb to include the latest jQuery and the Rails UJS adapter for jQuery:
    config.action_view.javascript_expansions[:defaults] = %w(http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js rails application)
    view raw application.rb hosted with ❤ by GitHub

    Update (May 4th) for jQuery 1.6:
    config.action_view.javascript_expansions[:defaults] = %w(http://code.jquery.com/jquery-1.6.min.js rails application)
    view raw application.rb hosted with ❤ by GitHub
  3. ...oh, I said 3 steps, right!
    Just continue building your application; here's an example: YouTube-like-comments.

2 comments:

  1. Or...

    1. put 'jquery-rails' in your Gemfile
    2. run 'bundle install'
    3. run 'rails g jquery:install'

    Tip you can pass --ui to the generator command to install jquery-ui too.

    Yes, this are 3 steps and you cheat to make it in two (1.5- Download rails ujs adapter for jquery)

    I like this approach better.

    ReplyDelete
  2. He he, thanks for the tip! ;o)

    ReplyDelete