在RailsGuides routing tutorial中,他们给出了以下示例
如何使用to
哈希参数设置简单路由:
get '/patients/:id', to: 'patients#show'
但是当你生成一个新的Rails应用程序(使用Rails 4.0.3)时
rails new
命令,生成的config/routes.rb
文件提供以下内容
使用散列键/值分隔符=>
get 'products/:id' => 'catalog#view'
定义路线的这些不同方法之间是否存在任何差异,或者 它们是一样的吗? The Rails documentation字面上这样说:
match 'path' => 'controller#action'
match 'path', to: 'controller#action'
match 'path', 'otherpath', on: :member, via: :get
也就是说,它并没有真正解释任何事情。
答案 0 :(得分:25)
使用to
与=>
定义路线之间没有功能差异
在Rails中。在内部,路由方法实际上转换了路由参数
表格
<method> '<path>' => '<controller>#<action>'
到这个表格
<method> '<path>', to: '<controller>#<action>'
以下是进行转换的实际源代码(来自Rails 4.0.4)
ActionDispatch::Routing::Mapper::Resources
module。注意每个
get
,post
等路由方法最终通过其参数传递
这个match
方法(评论我的):
def match(path, *rest)
# This if-block converts `=>` to `to`.
if rest.empty? && Hash === path
options = path
# The `find` method will find the first hash key that is a string
# instead of a symbol, e.g. `'welcome/index' => 'welcome#index'` instead
# of `to: 'welcome#index'`. By parallel assignment, `path` then becomes
# the value of the key, and `to` is assigned the value
# (the controller#action).
path, to = options.find { |name, _value| name.is_a?(String) }
# The following two lines finish the conversion of `=>` to `to` by adding
# `to` to the options hash, while removing the
# `'welcome/index' => 'welcome#index'` key/value pair from it
options[:to] = to
options.delete(path)
paths = [path]
else
options = rest.pop || {}
paths = [path] + rest
end
# More Code...
end