Frederik Spang Frederik Spang - 11 months ago 54
Ruby Question

Using same :as for two rails routes, with GET and POST for different actions

I've stumbled into this problem, where I'm trying to route my login paths, and I'm trying to achieve

GET /login
sends to
POST /login
sends to
. Although, Rails doesn't seem to recognize this as not a

get "/login" => "sessions#new", :as => :login
post "/login" => "sessions#create", :as => :login

This raises the following error on boot:

lib/action_dispatch/routing/route_set.rb:507:in 'add_route': Invalid route name, already in use: 'login' (ArgumentError)
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. For the latter, you can restrict the routes created with `resources` as explained here:

Would the best practice be to do a
resources :sessions, only: [:new, :create], as: :login
although I'd get URL Helpers like
and not just
as originally intended?

Answer Source

This is what I did on my Rails app.

get    'login'   => 'sessions#new'
post   'login'   => 'sessions#create'

I think the :as => :login part is what is causing your error, I think of that as assigning an alias, and you can't use the same alias for two different routes.