Rails 3.1.0.rc5
I am having trouble getting named routes to work within an ERB-enabled Javascript file:
# app/assets/javascripts/items.js.erb
$('#start').click(function() {
$.ajax({
url : '<%= ajax_items_path %>',
success : function(result) {
$('#result').html(result);
}
});
});
The error message is as follows:
Error compiling asset items.js:
NameError: undefined local variable or method `ajax_items_path' for #<#<Class:0x007fbcb49a7630>:0x007fbcb4ee30b8>
(in myproject/app/assets/javascripts/items.js.erb)
The ajax_items_path
route works fine if I use it directly in a view.
It looks like named routes aren't available within the Asset Pipeline. If this is the case, what is the workaround? I really want to avoid hard-coding URLs in my Javascript.
To compile your assets locally, run the assets:precompile task locally on your app. Make sure to use the production environment so that the production version of your assets are generated. A public/assets directory will be created. Inside this directory you'll find a manifest.
The asset pipeline provides a framework to concatenate and minify or compress JavaScript and CSS assets. It also adds the ability to write these assets in other languages such as CoffeeScript, Sass and ERB. Prior to Rails 3.1 these features were added through third-party Ruby libraries such as Jammit and Sprockets.
rails assets:precompile is the task that does the compilation (concatenation, minification, and preprocessing). When the task is run, Rails first looks at the files in the config.assets.precompile array. By default, this array includes application.js and application.css .
A workaround is to use your route helpers from Rails.application.routes.url_helpers
, e.g.
<%= Rails.application.routes.url_helpers.ajax_items_path %>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With