Rails default scripts and jquery-rails

I recently had an issue in a (3.0.7) rails app where link_to some_path, :method => :post was calling the action associated with GET, this was caused by not having a link to jquery_ujs.js (I'm using jquery so don't want rails.js) in my html output.

Googling turns up a number of suggestions to add jquery_ujs.js and the other jquery script files to the default javascripts by amending config/application.rb. This works ok but it's not ideal as you probably want minified versions of the files in production and non minified in development.

Digging into the jquery-rails gem reveals railtie.rb:

This sets the default scripts before config/application.rb is run. Unfortunatley with application.rb as it is generated if you run rails new with the -J switch (you probably don't want prototype if you plan to use jquery) these defaults are overridden. Commenting out

From config/application.rb allows the jquery-rails scripts to load but doesn't allow you to add to the defaults. I did submit a pull request amending the railtie to run it's code on before_initialize (after config/application.rb has been run). This allowed defaults to be set and the jquery defaults appended but as Indirect pointed out, this prevents you overriding the jquery defaults in application.rb.

The way to add your own scripts is to append them to the defaults using:

This works but there are 2 related issues; jquery_ujs.js should be the last script loaded as it needs to hook into any submission events for ajax elements and it can't unless scripts for those events are loaded before it.

With the solution above we have application.js (added by Rails) and our scripts loaded after jquery_ujs.js. Our scripts can be placed first by changing application.rb to:

This still leaves application.js loaded after jquery_ujs.js but that should be fine as long as there aren't any submission events scripted in it.

Using the railtie to set the default scripts then allowing you to append or override these defaults is a neat solution by the jquery-rails gem, unfortunately it doesn't seem that many know about it as there seems to be a lot of advice to add the jquery script files directly in config/application.rb. It looks as these issues will go away in Rails 3.1 anyhow.

Previous
Previous

Changing Three Finger Swipe to Back in Lion

Next
Next

Rails Autoload and Ruby Require