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

时间:2016-09-08 15:28:57

标签: ruby-on-rails ruby rails-routing ruby-on-rails-5

我偶然发现了这个问题,我正在尝试路由我的登录路径,并且我正在尝试将GET /login发送到sessions#newPOST /login发送给{ {1}}。虽然,Rails似乎并不认为这不是一个

sessions#create

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

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: :loginlogin_index_path之类的网址助手而不仅仅是new_login_path最初的意图吗?

2 个答案:

答案 0 :(得分:1)

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

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

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

答案 1 :(得分:1)

您可以将一个块传递给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