[英]Facing the NameError when trying to include concerns in my rails 6 controller
我正在嘗試使用本教程創建一個小項目來練習 API 密鑰身份驗證。 我在 rails 項目的以下目錄中創建了一個問題。
應用程序/控制器/關注/api_key_authenticable.rb
module ApiKeyAuthenticatable
extend ActiveSupport::Concern
include ActionController::HttpAuthentication::Basic::ControllerMethods
include ActionController::HttpAuthentication::Token::ControllerMethods
attr_reader :current_api_key
attr_reader :current_bearer
# Use this to raise an error and automatically respond with a 401 HTTP status
# code when API key authentication fails
def authenticate_with_api_key!
@current_bearer = authenticate_or_request_with_http_token &method(:authenticator)
end
# Use this for optional API key authentication
def authenticate_with_api_key
@current_bearer = authenticate_with_http_token &method(:authenticator)
end
private
attr_writer :current_api_key
attr_writer :current_bearer
def authenticator(http_token, options)
@current_api_key = ApiKey.find_by token: http_token
current_api_key&.bearer
end
end
在我的 Controller 中,我試圖包括這樣的問題
應用程序/控制器/ApiKeysController.rb
class ApiKeysController < ApplicationController
include ApiKeyAuthenticatable
# Require token authentication for index
prepend_before_action :authenticate_with_api_key!, only: [:index]
# Optional token authentication for logout
prepend_before_action :authenticate_with_api_key, only: [:destroy]
def index
end
def create
end
def destroy
end
end
但是當我運行服務器並訪問 controller 的索引操作時,我收到以下錯誤
NameError (uninitialized constant ApiKeysController::ApiKeyAuthenticatable):
app/controllers/ApiKeysController.rb:10:in `<class:ApiKeysController>'
app/controllers/ApiKeysController.rb:2:in `<main>'
有人可以幫我解決這個問題嗎?
作者在這里。 您關注的文件名是authenticable
的,但您的模塊是authenticatable
的。 您需要更正關注文件名中的拼寫錯誤。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.