使用相同的 :as 用于两个 rails 路由,GET 和 POST 用于不同的操作

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

我无意中遇到了这个问题,我正在尝试路由我的登录路径,我正在尝试实现 GET /login 发送到 sessions#newPOST /login 发送至 sessions#create。虽然,Rails 似乎不认为这不是

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

这会在启动时引发以下错误:

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

最好的做法是做一个 resources :sessions, only: [:new, :create], as: :login 虽然我会得到 URL 像 login_index_pathnew_login_path 这样的助手,而不仅仅是 login_path原本打算?

这就是我在 Rails 应用程序中所做的。

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

我认为 :as => :login 部分是导致错误的原因,我认为这是分配别名,并且您不能对两条不同的路由使用相同的别名。

您可以将区块传递给 scope:

scope as: 'login' do
  get "/login" => "sessions#new"
  post "/login" => "sessions#create"
end

这也适用于带参数的路由,例如:

scope as: 'post' do
  patch  '/posts/:id' => 'posts#update'
  put    '/posts/:id' => 'posts#update'
  delete '/posts/:id' => 'posts#destroy'
end

这导致:

$ rails routes -c post
Prefix Verb   URI Pattern            Controller#Action
post PATCH    /posts/:id(.:format)   posts#update
     PUT      /posts/:id(.:format)   posts#update
     DELETE   /posts/:id(.:format)   posts#destroy