Marty
Marty

Reputation: 2224

How to build a route that has a `#` in it?

How can you build a route with a hashtag (#) in it? I created the route

get 'authors/#/:id' => 'authors#show

But this generates the route

GET    /authors/%23/:id(.:format)

So it has %23 where the # should be.

Upvotes: 4

Views: 244

Answers (1)

smathy
smathy

Reputation: 27961

You can't use # in a URL on the server, it's call a Fragment Identifier and is a local in-page anchor which a browser will never send to the server.

Update

OP added information in comment re client-side routing.

Yes, while this makes no sense on the server-side of your app, you can absolutely have client-side routes with hashes in them. Modern browsers (HTML5 support) even have a hashchange event that you can bind to, although because older browsers don't support that then you will generally use a hashchange plugin for jQuery, or perhaps Angular supports this itself.

The idea is that basically the browser can detect the URL change and because the # change never triggers a request to the server then this is a convenient way to trigger changes in your client-side app without triggering a server request.

Another Update

After another comment from OP...

There is nothing at all for you to do on the server side. If your front-end guy wants to use a #-based URL like /authors#123 to trigger a client-side load of that author then his JS would be listening for that hashchange and then he would make a regular, non-hash-containing, request to the server like GET /authors/123.json and then would use the response from that to update the HTML of the loaded page.

Upvotes: 7

Related Questions