在Rails路由中使用"to:"和fat-arrow"=>"有什么区别?

17 ruby ruby-on-rails

RailsGuides路由教程中,他们提供了以下使用tohash参数设置简单路由的示例:

get '/patients/:id', to: 'patients#show'
Run Code Online (Sandbox Code Playgroud)

但是当您使用该rails new命令生成新的Rails应用程序(使用Rails 4.0.3)时 ,config/routes.rb生成的文件使用散列键/值分隔符提供以下简单路径示例=>

get 'products/:id' => 'catalog#view'
Run Code Online (Sandbox Code Playgroud)

这些不同方法之间是否存在定义路径的差异,或者它们是否相同? Rails文档字面上说:

match 'path' => 'controller#action'
match 'path', to: 'controller#action'
match 'path', 'otherpath', on: :member, via: :get
Run Code Online (Sandbox Code Playgroud)

也就是说,它并没有真正解释任何事情.

小智 25

使用tovs =>在Rails中定义路由之间没有功能差异.在内部,路由方法实际上转换了表单的路由参数

<method> '<path>' => '<controller>#<action>'
Run Code Online (Sandbox Code Playgroud)

这种形式

<method> '<path>', to: '<controller>#<action>'
Run Code Online (Sandbox Code Playgroud)

源代码

以下是在ActionDispatch::Routing::Mapper::Resources模块中进行转换的实际源(来自Rails 4.0.4) .需要注意的是每一个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
Run Code Online (Sandbox Code Playgroud)