A
A
Anton Misyagin2015-05-27 15:55:16
Ruby on Rails
Anton Misyagin, 2015-05-27 15:55:16

How to set path from routes.rb in my file.js?

For example, there is a file written in JavaScript. Put in the public folder. And attached later in the header. In this file, for example, there are some calls to the server (ajax). These calls go to addresses that are hardwired into this file. Then I change some route in routes.rb and I have to sit and remember in what place that could break because of this. The question is how to do something like:
file.js.erb

$.get(<%= send_sms_path %>, function(data){
 javascript_statements
})

This is question #1, and question #2 is a more complex version of my first question:
file.js.erb , where i is computed in the user's browser. Really? Or do you have to manually
$.get(<%= send_sms_path(i) %>)

Answer the question

In order to leave comments, you need to log in

2 answer(s)
G
gsmetal, 2015-06-11
@gsmetal

There is a gem: js-routes . You can set up regulars which paths to turn on / off, support for parameters, as in rail helpers, etc.
As a result, the paths are displayed simply:

Routes.user_project_path(1,2, {q: 'hello', custom: true}) // => "/users/1/projects/2?q=hello&custom=true"

M
Mikhail Osher, 2015-05-27
@miraage

Call the helper in the template.
The helper, in turn, will output routes in JSON format, like these:

window.routes = {
  send_sms_path: ['GET', '/send/sms/:id']
};

// EDIT
<!-- где-то внутри вьюхи -->
<%= render_routes %>

# ApplicationHelper.rb
def render_routes
  # Тут надо взять текущие роуты, создать из них хэш, пропусть его через JSON.generate и выплюнуть отсюда 
  # что-то вроде "<script>window.routes = #{JSON.generate roues};</script>"
end

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question