Created: 2008-05-20 03:36
Updated: 2016-05-11 21:31
License: mit


Named Routes in Javascript

This "creatively" named plugin installs a controller and view which creates handy javascript methods for generating named routes in javascript. For example, if you had the following RESTful route defined in routes.rb:

map.resources :posts

You'd get these (and other) familiar-looking javascript URL helpers, as methods under the Routing object:

Routing.posts_url()         => "http://localhost:3000/posts"
Routing.post_url({id: 3})   => "http://localhost:3000/posts/3"
Routing.post_path({id: 3})  => "/posts/3"
	id: 3, 
	format: 'xml'
})                          => "/posts/3.xml"

The hostname is available thru the "host" attribute of Routing:

Routing.host                => "http://localhost:3000"

The javascript generated by this plugin does not depend on any third-party javascript library.


Assuming you are using Rails 2.1 or later, you can use the Rails plugin script:

$ script/plugin install git://github.com/ripta/js_named_routes.git

This plugin is targeted at Rails 2.1, although it works in Rails 2.0. Earlier versions of Rails may work with this plugin, although not primarily supported.


This plugin automatically injects a route for the included JS named routes controller.

Install, and then visit the following URL:


Include the js_named_routes javascript URL in your HTML head tag (probably application.html.erb or other layout file):

<%= javascript_include_tag :named_routes %>

The route will be automatically installed in the :defaults route:

<%= javascript_include_tag :defaults %>

Just like in Rails, if you specify route segments that aren't part of the route will be added as query parameters:

Routing.post_url({id: 3, extra: 'string'})  => 'http://localhost:3000/posts/3?extra=string'
Routing.post_path({id: 3, extra: 'string'}) => '/posts/3?extra=string'

This plugin uses page caching to cache the generated javascript routes, but lacks any intelligence for sweeping the cached file if you've made changes to your routes. That shouldn't be a problem if you are using Capistrano for production deployments because the cache is normally stored in RAILS_ROOT/public which is not kept across deployments. Caching is normally disabled in development mode, but if you turn on caching you may need to manually clear the cached file:

$ rm public/javascripts/named_routes.js


Originally authored by Joshua Siereles with some code and the idea coming from Using Rails Routes from Client-Side JavaScript by Galen O'Hanlon.

Some enhancements and Rails 2.1 compatibility added by Galen O'Hanlon.

Routing object wrapper and Rails 2.0 compatibility added and cleaned up by Ripta Pasay.

Cookies help us deliver our services. By using our services, you agree to our use of cookies Learn more