[英]Facing the NameError when trying to include concerns in my rails 6 controller
I am trying to create a small project for practising the API Key Authentication using the this tutorial.我正在尝试使用本教程创建一个小项目来练习 API 密钥身份验证。 I have created a concern in following directory of the rails project.
我在 rails 项目的以下目录中创建了一个问题。
app/controllers/concerns/api_key_authenticable.rb应用程序/控制器/关注/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
In my Controller, I am trying to include the concern like this在我的 Controller 中,我试图包括这样的问题
app/controllers/ApiKeysController.rb应用程序/控制器/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
But when I run the server and visit the index action of the controller, I get the following error但是当我运行服务器并访问 controller 的索引操作时,我收到以下错误
NameError (uninitialized constant ApiKeysController::ApiKeyAuthenticatable):
app/controllers/ApiKeysController.rb:10:in `<class:ApiKeysController>'
app/controllers/ApiKeysController.rb:2:in `<main>'
Can anybody help me out to fix this issue?有人可以帮我解决这个问题吗?
Author here.作者在这里。 Your concern's filename is
authenticable
but your module is authenticatable
.您关注的文件名是
authenticable
的,但您的模块是authenticatable
的。 You'll need to correct the typo in the concern filename.您需要更正关注文件名中的拼写错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.