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.
A workaround is to use your route helpers from Rails.application.routes.url_helpers
, eg
<%= Rails.application.routes.url_helpers.ajax_items_path %>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.