Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How may two routes with different HTTP request types share the same name?

In Rails 3.2 I am using these routes declarations:

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

They result in (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"}

Now Rails 4.0 complains about this configuration:

Invalid route name, already in use: 'contact' You may have defined two routes with the same name using the :as option, or you may be overriding a route already defined by a resource with the same naming.

Obviously the routes share the same name, but as the request types differ, I'd expect them to be accepted as before.

How can I tell Rails 4 to generate the routes just like before in 3.2?

like image 303
user569825 Avatar asked Oct 04 '13 19:10

user569825


3 Answers

In your situation simply not specifying the :as option is sufficient as Rails will automatically get the route name from the path:

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

However if you have a more complex path pattern or want to refer to the route with a different name then you should specifically set the second route to :as => nil (or as: nil using the new hash syntax).

So if you wanted to name the route as person_path you would need to do:

get 'contact' => 'contact#new', :as => 'person'
post 'contact' => 'contact#create', :as => nil
like image 170
Richard Strand Avatar answered Nov 16 '22 22:11

Richard Strand


If these two routes have the same URL, you don't need to name the second one. So the following should work:

get 'contact' => 'contact#new', :as => 'contact'
post 'contact' => 'contact#create'
like image 43
Marek Lipka Avatar answered Nov 16 '22 21:11

Marek Lipka


Why do you use the :as ? It seems to be not needed in this case.

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

gives

Prefix Verb URI Pattern        Controller#Action
contact GET  /contact(.:format) contact#new
        POST /contact(.:format) contact#create
like image 20
loog Avatar answered Nov 16 '22 20:11

loog