views:

30

answers:

1

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.

+1  A: 

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

  1. Create javascript templates in (say) lib/javascripts using ERB named like '*.js.erb' and a rake task to expand those templates into public/javascripts 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 file
  2. Create per-view javascript helper functions in a content_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) {

});
bjg
Thank for your help. But if I want to access them in my public/javascript files , How can I access them.
kishore