Rails路线-斜线字符vs哈希字符 [英] Rails Routes - slash character vs hash character
问题描述
在url和rails路由中,使用斜杠字符与井号(井号)字符有什么区别?
In urls and rails routing, what is the difference between using a slash character vs a pound sign (hash sign) character?
这些工作
get "/static_pages/about"
get 'about', to: 'static_pages#about', as: :about
这些不是
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?
答案:
(两个人回答得很好,我很难选择哪个标记为
(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.
推荐答案
中的
表示#
可以:' static_pages#about' static_pages_controller
的 about
个动作。语法为 controller#action
。
The #
in to: 'static_pages#about'
means about
action of static_pages_controller
. The syntax is controller#action
.
定义时,获取 / static_pages#about
, static_pages#about
成为路线的控制者,即#
只是一个字符文字和<$ c $ c> #about 并不表示 about
动作。如果 static_pages#about
控制器不存在,则应该出现 missing:controller
错误。
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.
以下路线定义为您提供 / about
路径,该路径映射到 static_pages / about
控制器的 about
动作,其中 static_pages
可以是名称空间或范围。
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
这篇关于Rails路线-斜线字符vs哈希字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!