I’m using this javascript in substitution of remote_action:
$(document).ready(function() {
$('#asset_category_id').change(function() {
$.ajax({
url : '<%= escape_javascript(url_for :controller => :categories, :action => :update_subcategories) %>',
data : 'category_id=' + this.value,
success : function(data) {
$('#subcategories_div').html(data);
$('#subcategories_div').show();
}
})
});
});
The url in the following line is not being formed correctly:
url : '<%= escape_javascript(url_for :controller => :categories, :action => :update_subcategories) %>'
It is being used literally:
How can I use url_for in jQuery? Is it possible?
If I use
url : '/categories/update_subcategories'
everything runs as expected.
EDIT:
I have tried the following things without luck.
Seems that I should use preprocessing (guides.rubyonrails.org/asset_pipeline.html#preprocessing) as noted by @Matzi and @Baldrick so my file should be main.js.erb. I have renamed this file in app/assets/javascripts. When I go to the assets/new view (where the file is needed) I get this error:
undefined method 'url_for' for #<#<Class:0x9853e4c>:0xab00c48>
I’ve tried to add these two lines to the assets_controller:
include ActionView::Helpers::UrlHelper
include ActionView::Helpers::TagHelper
Then I get:
undefined local variable or method `controller' for #<AssetsController:0xa40aaec>
In this line of the view:
<%= form_for(@asset) do |f| %>
I have also tried to add these lines to the new.html.erb file:
<%= include ActionView::Helpers::UrlHelper %>
<%= include ActionView::Helpers::TagHelper %>
Then I get:
undefined method `include' for #<#<Class:0xab164d0>:0xab0183c>
As recommended by Rails 3: How to render ERb template in rake task? in a similar case. I have tried the following includes in the view and controller with the same results:
include Rails.application.routes.url_helpers # brings ActionDispatch::Routing::UrlFor
include ActionView::Helpers::TagHelper
Another thing that I’ve tried, recommended by @Matzi is moving main.js.erb from app/assets/javascripts/ to app/views/assets. But in that case the Javascript in main.js.erb seems not to be loaded at the same time that the view new.html.erb. I’ve tried to rename main.js.erb to new.js.erb but the JS in the file seems not to be loaded neither.
I have though in using a JS to attach the handler and a js.erb to return the result but I need the url_for in the first JS in order to know where to call.
So the question remains, how can I use url_for in a js.erb that tries to attach a change handler to a field in a view?
I think the problem is that it is in a .js file, which is not interpreted by ruby. Try to put this code in a .js.erb file, and it will work for you.
UPDATE:
Asset is not for this kind of dynamic behavior, so you would better move it into some view, and render it, when needed. If you want to use it in an asset, you need to include the helpers in the .js.erb: