Rails route URL helpers in JavaScript

503 views
Skip to first unread message

Bogdan Gusiev

unread,
Jan 25, 2019, 9:08:08 AM1/25/19
to Ruby on Rails: Core
Good Morning,

Rails route URL helpers are great. Their API is concise and intuitive.
I believe that we should have that API available in Javascript too:

users_path()                                       // => "/users"
user_path
(1)                                       // => "/users/1"
user_path
(1, {format: 'json'})                     // => "/users/1.json"
user_path
(1, {anchor: 'profile'})                  // => "/users/1#profile"
new_user_project_path
(1, {format: 'json'})         // => "/users/1/projects/new.json"
user_project_path
(1,2, {q: 'hello', custom: true}) // => "/users/1/projects/2?q=hello&custom=true"
user_project_path
(1,2, {hello: ['world', 'mars']}) // => "/users/1/projects/2?hello%5B%5D=world&hello%5B%5D=mars"



Most Rails projects I know hardcode routes in Javascript, some pass those routes from HTML as data attributes.
Like:

jQuery.get("/posts/" + post.id + "/comments/" + comment.id + ".json", function(){ ...});
// slightly better
jQuery.get($(this).data("url"), function(){ ...});




But I believe that extensive use of JS should require URL helpers. 

Here is the "prototype" 8 years old project I maintain: https://github.com/railsware/js-routes
But I believe 90% of Rails projects need that out of the box now.

What do you think about adding the functionality to the Rails core?


Andrew Kaspick

unread,
Jan 25, 2019, 9:16:04 AM1/25/19
to Ruby on Rails: Core
I've generally got around this issue by including helper generated urls in data-* attributes or in json generated on the server, but perhaps there's situations where those solutions don't work.

--
You received this message because you are subscribed to the Google Groups "Ruby on Rails: Core" group.
To unsubscribe from this group and stop receiving emails from it, send an email to rubyonrails-co...@googlegroups.com.
To post to this group, send email to rubyonra...@googlegroups.com.
Visit this group at https://groups.google.com/group/rubyonrails-core.
For more options, visit https://groups.google.com/d/optout.

DHH

unread,
Jan 29, 2019, 2:55:08 PM1/29/19
to Ruby on Rails: Core
We use data-url attributes alongside Stimulus at Basecamp. I don't see that a JS router is something we'd ship by default. But great to have that as a gem 👍

Piotr Szmielew

unread,
Jan 29, 2019, 4:20:27 PM1/29/19
to rubyonra...@googlegroups.com
I feel that exposing all routes through JS would be a huge security issue. 

Using data URL attributes would be fine - exposing only routes available to the current user.

Andrew Kaspick

unread,
Jan 29, 2019, 4:26:24 PM1/29/19
to Ruby on Rails: Core
I use data-* attributes as well or pass the urls back to the client via json generated on the server.
Reply all
Reply to author
Forward
0 new messages