Route with as: '/' (slash)

I have namespace in my routes file:

namespace :admin do
  root to: 'posts#index', as: '/'
  resources :posts, except: :show
  resources :users, except: :show
  resources :apps, except: :show
end

I’m a little confused about the as: '/' part. The / (slash) seems to evaluate to nothing. For example, if i rewrite the route as:

root to: 'posts#index', as: ''

The route appears to be the same. I guess I’m just looking for some validation that this is, in fact, ok and I’m not going to get burned later. I can’t seem to find any documentation on it.

You shouldn’t need the as: '/' part at all: The as argument names the route so that you can use route helpers. It’s the root part that says this is the root URL, i.e. the URL at ‘/’.

For example, if you had this in your routes file:

namespace :admin do
  root to: 'posts#index', as: 'foo'
end

Rails would define a method called admin_foo_path that would return "/admin". If you leave off the as entirely then Rails will define an admin_root_path helper that returns "/admin".

Hope that helps!

Thanks @georgebrock! You’re right, I don’t need the as: part at all, but it does change the helper from admin_path to admin_root_path. Not a big deal, I could change that in a few places. Mostly I was wondering why '/' worked at all.

Ah, sorry, I misunderstood your original question.

The as parameter is passed through the ActionDispatch::Routing::Mapper.normalize_name method, which makes sure it’s a suitable route name. This converts "/" to "":

> ActionDispatch::Routing::Mapper.normalize_name('/')
=> ""

This normalised version of the name (in your case an empty string) is added to an array with the namespace to give ["admin", ""], and then any blanks are filtered out, and the results are joined, leaving us with the final route name: "admin"

I’d still suggest dropping the as though: It’s usually clearer to stick with the Rails convention unless there’s a good reason not to, it means there are fewer surprises when an unfamiliar developer works on the app.

Awesome @georgebrock! Thank you so much. That’s exactly what I was looking for. You’re probably right about just dropping the as too. I’ll reconsider my setup to see why I did that in the first place. :smile: