Use Rails URL Helper with Javascript

Reading Time: 2 minutes

Sometimes in some projects that I worked on I needed to use Rails URLs inside my JS, but I couldn't do this directly because, as you know, we need to integrate our scripts in some .erb file to be able to use them. So, to save you some time, you can use this gem.


gem "js-routes"


Require the js routes file in application.js or other manifest:

= require js-routes

Also in order to flush asset pipeline cache, sometimes you might need to run:

rake tmp:cache:clear

You have an advance setup mode adding config/initializers/jsroutes.rb to your initializers. To see all the available options you can modify, click here.


Configuration above will create a nice javascript file with Routes object that has all the Rails routes available:

Routes.users_path() // => "/users"
Routes.user_path(1) // => "/users/1"
Routes.user_path(1, {format: 'json'}) // => "/users/1.json"

This is how you can use a serialized object as a route function argument:

var google = {id: 1, name: "Google"};
Routes.company_path(google) // => "/companies/1"

Advanced Setup

In case you need multiple route files for different parts of your application, you have to create the files manually. If you have in your application an admin and an application namespace for example:

# app/assets/javascripts/admin/routes.js.erb
<%= JsRoutes.generate(namespace: "AdminRoutes", include: /admin/) %>

# app/assets/javascripts/
#= require admin/routes
# app/assets/javascripts/application/routes.js.erb
<%= JsRoutes.generate(namespace: "AppRoutes", exclude: /admin/) %>

# app/assets/javascripts/
#= require application/routes

This gem is nice to have on any project, because it gives you the possibility to use the Rails URL helpers on your fronted, you don't need to work anymore on .erb files to be able to use Rails paths inside your js scripts, making it extremely helpful.

I hope this helps you and saves you time and effort. Remember to contribute on the gem if you have any ideas to improve it, or even better: create your own gems to solve other problems and tell us about them!

Post any questions or comments below, we're happy to read you.


You May Also Like
Read More


Reading Time: 2 minutes Disclaimer ActiveRecord::Observer will be extracted to a separated gem when Rails 4 is released, so if you are…
Read More

Active Job

Reading Time: 3 minutes Hey guys! I hope you are doing great. Recently I worked on a Spree extension to index products…