Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing rails routes in javascript

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.

like image 758
kishore Avatar asked Jul 15 '10 16:07

kishore


People also ask

How do I see routes in Rails?

TIP: If you ever want to list all the routes of your application you can use rails routes on your terminal and if you want to list routes of a specific resource, you can use rails routes | grep hotel . This will list all the routes of Hotel.

Can you use JavaScript with Ruby on Rails?

Rails uses a technique called "Unobtrusive JavaScript" to handle attaching JavaScript to the DOM. This is generally considered to be a best-practice within the frontend community, but you may occasionally read tutorials that demonstrate other ways.

How do routes work in Rails?

Rails routing is a two-way piece of machinery – rather as if you could turn trees into paper, and then turn paper back into trees. Specifically, it both connects incoming HTTP requests to the code in your application's controllers, and helps you generate URLs without having to hard-code them as strings.

What is Rails Ujs?

Rails UJS (Unobtrusive JavaScript) is the JavaScript library that helps Rails do its magic when we use options like remote: true for many of the html helpers. In this article I'll try to explain the main concept of how this works to make it transparent for the user.


2 Answers

I was researching this question for a while and didn't found any implementation compatible with Rails 3.

So decided to write my own:

https://github.com/railsware/js-routes

like image 80
Bogdan Gusiev Avatar answered Oct 08 '22 21:10

Bogdan Gusiev


kishore I think this is the simpliest way, just call:

Rails.application.routes.url_helpers.*_path

So, if you have in your routes.rb, let's say:

resources :users

then you want to call the index action from a javascript file, you do:

$.get('<%= Rails.application.routes.url_helpers.users_path %>', function(data){ ... 

Take into account that the js file should have a .erb extension (or *.js.erb) so rails knows that must be preprocessed. Otherwise, the file will be served as is.

like image 27
rapofran Avatar answered Oct 08 '22 22:10

rapofran