Hi
Can anyone explain how i can access the rails routes/names routes in javascript ?
The following are some of the things i tried http://github.com/jsierles/js_named_routes.
but no luck.
Hi
Can anyone explain how i can access the rails routes/names routes in javascript ?
The following are some of the things i tried http://github.com/jsierles/js_named_routes.
but no luck.
If I understand your requirement correctly you want Javascript code in your views to have access to the named routes. If so, then one simple way to do this is to render your Javascript code through a template (ERB, Haml, etc) and then to expand the routes something like the following:
ERB:
<script>
$.get('<%= some_named_route_path %>', function(data) {
});
</script>
Haml:
:javascript
$.get('#{ some_named_route_path }', function(data) {
});
UPDATE: Adding suggestions for public/javascripts/
case
Accessing named routes from the public folder is a bit trickier but there at least 2 ways that come to mind, neither of which is entirely satisfactory but, one or either of which might suit your application
lib/javascripts
using ERB named like '*.js.erb'
and a rake
task to expand those templates into public/javascript
s before deploying (say as a step in your Capistrano recipe for example). Downside of that is that your changes are not made available live on the site until the templates are expanded and you might not get the right syntax highlighting of your javascript with an .erb
extension filecontent_for :head
block which expand the named routes and make those available to code from your public javascript files. If you're careful with namespacing and conventions this might work out well. The downside is that the code calling these javascript helpers is decoupled from the code that defines them which could be confusing for maintainers or prone to abuse.In some view:
<% content_for :head do %>
<script>
SomeNameSpace.helper_to_some_named_route = function() {
return '%<= some_named_route_path %>
};
</script>
<% end %>
Then in public/application.js
(say)
$.get(SomeNameSpace.helper_to_some_named_route(), function(data) {
});