I’m working on a Rails project and I need to use Rails path helpers inside my JavaScript files. I have a file called app.js.coffee.erb
and I want to be able to call Rails route helpers from within it.
$('#input_field').attr('data-url', "<%= new_article_path %>")
What I’m hoping to get after ERB processing is something like:
$('#input_field').attr('data-url', "/articles/new")
Is this possible with Rails asset pipeline? I’ve tried a few approaches but can’t seem to get the helper methods to work properly in my JavaScript assets. Any suggestions on how to make this work?
You’ve got the .erb extension right, but you’re probably missing a key step. Rails needs the file extensions in the correct order: app.js.erb or app.js.coffee.erb if you’re using CoffeeScript. I hit this same problem last year. Had my extensions backwards - filename.erb.js instead of filename.js.erb. Rails processes extensions right to left, so ERB runs first, then it treats the result as JavaScript. Also check that your JavaScript file is actually required in your application manifest. Even with correct naming, ERB won’t process if it’s not included in application.js.
Another gotcha: the asset pipeline compiles these files during precompilation, so routes get baked in at compile time, not runtime. Works fine usually, but breaks if you’re deploying to different environments with different route configs. I always double-check that routes.rb is set up right and the helper I’m calling actually exists. You can verify this by checking the compiled asset in development - look at the generated JavaScript in your browser’s dev tools or check the compiled file directly. Still having issues? Try a simpler helper like root_path first to make sure basic ERB processing works before jumping into complex nested routes.
clear ur cache first - rails sometimes caches compiled assets n won’t pick up erb changes. delete tmp/cache or restart ur dev server. also check if ur using the right helper. some route helpers need specific params.