Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use jQuery instead of Prototype in a Rails 3 application?

I would like to use jQuery instead of Prototype in my Rails 3 application.

What is the "official" Rails 3 way to do this?

like image 596
Andrew Avatar asked Feb 19 '11 20:02

Andrew


2 Answers

First you need to install the gem, by adding this line to the Gemfile:

gem 'jquery-rails', '>= 0.2.6'

(and run bundle install) Then you need to go to the public/javascript folder and you need to replace the rails.js file by the one from: http://github.com/rails/jquery-ujs.

The proper way of doing this is to do:

rails generate jquery:install

or if you want to include jQuery UI:

rails generate jquery:install --ui

From the Github page:

This will remove the Prototype.js library from Rails, add latest jQuery library and fetch the adapter. Be sure to choose to overwrite the "rails.js" file.

like image 119
Amokrane Chentir Avatar answered Nov 02 '22 23:11

Amokrane Chentir


It's extremely easy.

First, get rails.js from from the bottom of this page. That page also has a good set of instructions.

Then, put rails.js and jQuery itself in the public/javascripts directory. You can clear out all other files from that directory.

Finally, in application.rb, add the following:

config.action_view.javascript_expansions[:defaults] = %w(jquery rails)

This assumes that your jQuery file is named jquery.js. That line tells Rails to automatically load jquery.js and rails.js whenever <%= javascript_include_tag :defaults %> is encountered.

That's it! Rails 3 automatically generates attributes on the elements jQuery needs to add events to, and jQuery reads those attributes and adds the necessary events.

like image 26
ClosureCowboy Avatar answered Nov 02 '22 23:11

ClosureCowboy