【问题标题】:How may two routes with different HTTP request types share the same name?具有不同 HTTP 请求类型的两条路由如何共享相同的名称?
【发布时间】:2013-10-11 22:27:04
【问题描述】:

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

get 'contact' => 'contact#new', :as => 'contact'
post 'contact' => 'contact#create', :as => 'contact'

它们导致 (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"}

现在 Rails 4.0 抱怨此配置:

无效的路由名称,已在使用:'contact' 您可能已经定义 使用:as 选项的两条同名路线,或者您可能是 覆盖已由具有相同资源的资源定义的路由 命名。

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

如何让 Rails 4 像以前在 3.2 中一样生成路由?

【问题讨论】:

    标签: ruby-on-rails ruby routes ruby-on-rails-4


    【解决方案1】:

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

    get 'contact' => 'contact#new'
    post 'contact' => 'contact#create'
    

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

    因此,如果您想将路线命名为 person_path,您需要这样做:

    get 'contact' => 'contact#new', :as => 'person'
    post 'contact' => 'contact#create', :as => nil
    

    【讨论】:

    • 我一直在期待这个:as => nil
    【解决方案2】:

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

    get 'contact' => 'contact#new', :as => 'contact'
    post 'contact' => 'contact#create'
    

    【讨论】:

    • 如果您将路线命名为不同的 as,则无效,例如,get 'contact' => 'contact#new', :as => 'some_other_thing' -- 不会被继承
    【解决方案3】:

    您为什么使用 :as ?在这种情况下似乎不需要。

    get 'contact' => 'contact#new'
    post 'contact' => 'contact#create'
    

    给予

    Prefix Verb URI Pattern        Controller#Action
    contact GET  /contact(.:format) contact#new
            POST /contact(.:format) contact#create
    

    【讨论】:

      猜你喜欢
      • 2014-10-07
      • 1970-01-01
      • 2013-10-09
      • 1970-01-01
      • 1970-01-01
      • 2023-04-10
      • 1970-01-01
      • 2015-02-19
      • 2015-08-18
      相关资源
      最近更新 更多