Rails Routes - slash character vs hash character

rails-routing, routes, ruby-on-rails, syntax, url

Solution

The `#` in `to: 'static_pages#about'` means `about` action of `static_pages_controller`. The syntax is `controller#action`.

When you define `get "/static_pages#about"`, `static_pages#about` becomes the controller for the route i.e. the `#` is only a character literal and `#about` does not mean `about` action. You should get a `missing :controller` error if `static_pages#about` controller does not exist.

The following route definition gives you `/about` path which maps to `static_pages/about` controller's `about` action, where `static_pages` could either be a namespace or a scope.

get 'about', to: 'static_pages/about', as: :about

The following route is invalid and should throw an error due to the leading slash `/` in `to` option.

get 'about', to: '/static_pages#about', as: :about

Problem

In urls and rails routing, what is the difference between using a slash character vs a pound sign (hash sign) character? These work ``` get "/static_pages/about" get 'about', to: 'static_pages#about', as: :about ``` These don't ``` get "/static_pages#about" get 'about', to: 'static_pages/about', as: :about get 'about', to: '/static_pages#about', as: :about ``` What code controls this behavior, and what is the deeper reason behind it? ANSWER: (The two people answered it very well, and I had trouble choosing which one to mark as the accepted answer. I wish to state my understanding of the answer in a different way that might help people.) Once you use the / symbol, the string gets recognized as a url string appended to the base url. So a '#' character will be interpreted as part of the url, and urls don't like to take '#' characters. In the case of not using a / character, the first word is recognized somehow as a controller name, which you follow up with a '#' and an action name.

Original source