问题
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.
回答1:
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
回答2:
In ruby, the hash symbol generally precedes the name of a instance method of a class. See the left sidebar of the page of the Array class documentation (http://www.ruby-doc.org/core-2.1.0/Array.html).
get "/static_pages#about"
doesn't work because #about
is not part of the url.
get 'about', to: 'static_pages/about', as: :about
doesn't work because /about
doesn't indicate which controller method should be called.
get 'about', to: '/static_pages#about', as: :about
doesn't work because of the preceding slash before static_pages.
来源:https://stackoverflow.com/questions/21372675/rails-routes-slash-character-vs-hash-character