Rails 找不到路径的 ApplicationController 抛出

Rails ApplicationController throwing not found for path

我在 routes.rb 中有以下内容:

Rails.application.routes.draw do
  resources :users, param: :email
  post '/auth/login', to: 'authentication#login'
  get '/*a', to: 'application#not_found'
  get '/attendance/in', to: 'attendances#in'
  get '/attendance/out', to: 'attendances#out'
  get '/user/get_attendance_status', to: 'users#get_attendance_status'
end

现在,例如,在我的 users_controller.rb 中,我有以下操作:

before_action :authorize_request

def get_attendance_status
  render json: { at_work: @current_user.at_work }, status: :ok
end

:authorize_requestapplication_controller.rb中定义如下:

class ApplicationController < ActionController::API
    def not_found
        render json: { error: 'not_found' }
    end

    def authorize_request
        header = request.headers['Authorization']
        header = header.split(' ').last if header
        begin
            @decoded = JsonWebToken.decode(header)
            @current_user = User.find(@decoded[:user_id])
            rescue ActiveRecord::RecordNotFound => e
                render json: { errors: e.message }, status: :unauthorized
            rescue JWT::DecodeError => e
                render json: { errors: e.message }, status: :unauthorized
        end
    end
end

现在,当我通过 Postman 向本地服务器提交请求时,出现以下错误:

Started GET "/user/get_attendance_status" for 58.177.56.127 at 2020-05-23 19:12:49 +0800
Processing by ApplicationController#not_found as HTML
  Parameters: {"a"=>"user/get_attendance_status"}
Completed 200 OK in 2ms (Views: 1.1ms | ActiveRecord: 0.0ms | Allocations: 93)


Started GET "/attendance/in" for 58.177.56.127 at 2020-05-23 19:13:14 +0800
Processing by ApplicationController#not_found as HTML
  Parameters: {"a"=>"attendance/in"}
Completed 200 OK in 1ms (Views: 0.3ms | ActiveRecord: 0.0ms | Allocations: 91)

如您所见,触发了application_controller#not_found,但为什么呢?我不确定为什么会这样。任何见解将不胜感激。

我不得不将 get '/*a', to: 'application#not_found' 路线移到底部,所以我的 routes.rb 现在看起来像这样:

Rails.application.routes.draw do
  resources :users, param: :email
  post '/auth/login', to: 'authentication#login'
  get '/attendance/in', to: 'attendances#in'
  get '/attendance/out', to: 'attendances#out'
  get '/user/get_attendance_status', to: 'users#get_attendance_status'
  get '/*a', to: 'application#not_found'
end

路由按出现顺序匹配,所以是的,您的 a* 路由应放在末尾。问题是你为什么需要这条路线? Rails 如果路由不存在,自动 returns 一个 404。