ruby-on-railsrubyrails-routingruby-on-rails-5

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 sessions#new and POST /login sends to sessions#create. 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: http://guides.rubyonrails.org/routing.html#restricting-the-routes-created

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


Solution

  • 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.