Reputation: 6317
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.
Upvotes: 12
Views: 2141
Reputation: 3357
A workaround is to use your route helpers from Rails.application.routes.url_helpers
, e.g.
<%= Rails.application.routes.url_helpers.ajax_items_path %>
Upvotes: 25