具有不同HTTP请求类型的两条路由如何共享相同的名称?

use*_*825 17 ruby routes ruby-on-rails ruby-on-rails-4

Rails 3.2中我使用这些路由声明:

get 'contact' => 'contact#new', :as => 'contact'
post 'contact' => 'contact#create', :as => 'contact'
Run Code Online (Sandbox Code Playgroud)

它们导致(rake routes):

contact_en GET    /en/contact(.:format)    contact#new {:locale=>"en"}
contact_de GET    /de/kontakt(.:format)    contact#new {:locale=>"de"}
contact_en POST   /en/contact(.:format)    contact#create {:locale=>"en"}
contact_de POST   /de/kontakt(.:format)    contact#create {:locale=>"de"}
Run Code Online (Sandbox Code Playgroud)

现在Rails 4.0抱怨这个配置:

无效的路由名称,已在使用中:'contact'您可能已使用该:as选项定义了两个具有相同名称的路由,或者您可能正在覆盖已由具有相同命名的资源定义的路由.

显然,路由共享相同的名称,但由于请求类型不同,我希望它们像以前一样被接受.

如何告诉Rails 4在3.2中生成路由?

Ric*_*and 14

在您的情况下,只需不指定:as选项就足够了,因为Rails会自动从路径中获取路径名称:

get 'contact' => 'contact#new'
post 'contact' => 'contact#create'
Run Code Online (Sandbox Code Playgroud)

但是,如果您有一个更复杂的路径模式或想要引用具有不同名称的路由,那么您应该专门设置第二个路由:as => nil(或as: nil使用新的哈希语法).

因此,如果您想根据需要命名路线person_path:

get 'contact' => 'contact#new', :as => 'person'
post 'contact' => 'contact#create', :as => nil
Run Code Online (Sandbox Code Playgroud)

  • 嘿,大家好,这是正确的答案:) (4认同)
  • 我一直在想这个`:as => nil` (2认同)

Mar*_*pka 11

如果这两个路由具有相同的URL,则无需为第二个路由命名.所以以下应该有效:

get 'contact' => 'contact#new', :as => 'contact'
post 'contact' => 'contact#create'
Run Code Online (Sandbox Code Playgroud)

  • 如果您将路由命名为其他“ as”,则无效,例如,“ get'contact'=>'contact#new',:as =>'some_other_thing'`-不会被继承 (2认同)