重定向到GET路径(Rails自动假定我正在尝试PUT)

时间:2019-07-19 06:07:08

标签: ruby-on-rails routing

我在routes.rb中设置了登录路径(这是Sorcery外部模块的一部分):

# routes.rb
Rails.application.routes.draw do
  get 'oauth/:provider', to: 'oauths#oauth', as: :auth_at_provider
end

当响应为unauthorized(状态代码为401)并且用户需要重新登录时,我想在其他控制器之一中重定向到此路由。

# foo_controller.rb
class Web::FooController < ApplicationController
  def action_that_needs_login
    response = HTTParty.get(external_api_url,
      headers: {
        'Content-Type' => 'application/json',
        'Authorization' => "Bearer #{access_token}"
      })
  redirect_to auth_at_provider_path(:provider => :google) if response['error']['code'] == 401
  end
end

但是,出于某种原因,Rails似乎假设我要发送PUT请求。为什么会这样,如何纠正它以发送GET请求?

控制台日志:

Started PUT "/oauth/google" for ::1 at 2019-07-19
ActionController::RoutingError (No route matches [PUT] "/oauth/google")

[更新] 这是rails routes中的相关路线:

         Prefix Verb URI Pattern                 Controller#Action
auth_at_provider GET /oauth/:provider(.:format)  oauths#oauth

[更新#2] ,我也尝试像这样手动指定路由,但这没有用,因为重定向路由位于其他名称空间中。

redirect_to controller: 'oauths', action: 'oauth', provider: :google

这将返回ActionController::UrlGenerationError (No route matches {:action=>"oauth", :controller=>"web/oauths", :id=>"5", :provider=>:google})

1 个答案:

答案 0 :(得分:0)

尝试在resources.rb中的资源中定义它

resources :oauths, only: [] do 
  collection do
    get 'oauth/:provider', as: :auth_at_provider
  end
end

让我知道是否有帮助?