How do we access rails routes from Javascript erb file?

In my case the Javascript file name was: application.js.erb and I needed to do an ajax call like below:
$.ajax("<%=regions_path%>", {data: {country_id: countryId}
But rails was not happy about the route path. It was not recognizing the route path. Then I realized that all the routes are available through Rails.application.routes.url_helpers.
Then I called same ajax like below and it worked:
$.ajax("<%=Rails.application.routes.url_helpers.regions_path%>",
 {data: {country_id: countryId}
We can make this available so that all the rails route will working in usual way. We just need to write the following line in the js.erb file to make it available.
<% environment.context_class.instance_eval { 
include Rails.application.routes.url_helpers } %>
Now the usual rails rake routes path will work nicely. The following call will work too:
$.ajax("<%=regions_path%>", {data: {country_id: countryId}

Comments