The setup process differs depending on whether your app is running on a version of Rails before 3.1 or after 3.1.
Before Rails 3.1:
For political reasons, Rails has always shipped with the Prototype library instead of jQuery. The last "Rails Survey" showed that around 70% of projects were using jQuery instead. Developers install the library and override the default Prototype.
You could setup the library yourself, but that is too much work. Instead, rely on the official
gem 'jquery-rails' to your
Gemfile then run
Running the Generator
From your project’s directory, run the generator:
The generator will remove the Prototype libraries and install the latest version of jQuery:
Note that the
jquery_ujs.js is a replacement for the
rails.js which handles functions like making your delete links work.
That will load jQuery on all your pages.
After Rails 3.1
jquery-rails is automatically included in your
Gemfile and running the generator is not necessary.
Before Rails 3.1
application.js file there which is included in the Rails defaults.
You have two options for loading those additional files. The first is to just add them to the layout:
This is a good choice if you want to be explicit and especially if you want to load different JS files for different pages/layouts.
You could choose to change the definition of
:defaults. In your
config/application.rb you would add this:
Or, if you are managing a large number of JS files, you might define your own expansion name. In
Then in the layout:
Rails 3.1 and Beyond
app directory so it was closer to the Ruby application code.
Enter the Pipeline
The solution to both of these issues is the Asset Pipeline. The pipeline allows us to assemble multiple JS files server side, minify and compress them, and then output a single file to the browser. This results in just one request/response cycle, lower total I/O, and faster processing on the client. The component files live in the
app directory and mirror the structure of other components.
The Rails 3.1 generators are set up to help you. When you generate an
ArticlesController, for instance, it will create
.coffee? Next we will take a look at CoffeeScript.
Use the Blogger sample application to complete the exercises in this section. See the Setup Instructions for help.
- Add the
jquery-railsgem to Blogger and use the generator to setup the library.
- Create a file named
- Load that file by adding it to the include in the application layout. Verify it is in the head by looking at the page source.
- Remove it from the application layout, and instead add it to the
:defaultsin the configuration. Note that you’ll need to restart the server for it to take effect. Verify the script appears in the head of a page’s source.
- CHALLENGE: Write the jQuery in
interface.jsso that clicking the "Comments" header toggles the visibility of all comments.