修复 rails 5 匹配路由的弃用警告

Fixing rails 5 deprecation warning for matching routes

在我的 routes.rb 文件中,我有以下内容

  resources :landings, only: [:index],
    path: '/golf' do
      collection do
        get 'break_70', path: 'how-to-break-70'
      end
  end

生成 url

/golf/how-to-break-70

升级到 Rails 5 后,将生成以下弃用消息:

DEPRECATION WARNING: Specifying strings for both :path and the route path is deprecated. Change things like this:
  match "break_70", :path => "how-to-break-70"
to this:
  match "how-to-break-70", :as => "break_70", :action => "break_70"

如果我尝试按照这些说明

 resources :landings, only: [:index],
    match: '/golf' do
      collection do
        match: 'how-to-break-70', as: 'break_70', action: 'break_70'
      end
  end

然后我得到以下错误

syntax error, unexpected ':', expecting keyword_end
        match: 'how-to-break-70', as: 'break_70', action: 'break_70'

如何修改此路由以避免弃用警告?

更新答案
我更新了我的答案以修复一个小错误,因此任何 reader 都可以看到有效的代码。感谢@Obromios 的小修复。

resources中应该还是path:。 在路由定义中,在 match 之后有一个额外的“:”。如果 match.
,则还必须指定 via: [:get, :post] 所以最终版本看起来像:

resources :landings, only: [:index], path: '/golf' do
  collection do
    match 'how-to-break-70', as: 'break_70', action: 'break_70', via: [:get, :post]
  end
end

原答案

resources中应该还是path:。 在路由定义中,你在 match 之后有一个额外的“:” 所以最终版本看起来像:

resources :landings, only: [:index], path: '/golf' do
  collection do
    match 'how-to-break-70', as: 'break_70', action: 'break_70'
  end
end

未测试,但应该可以。