【问题标题】:Uninitialized constant error in Rails controllerRails 控制器中未初始化的常量错误
【发布时间】:2020-09-14 10:27:44
【问题描述】:

我有以下命名空间 ApiController

class Api::ApiController < ApplicationController
  skip_before_action :verify_authenticity_token, 
  if: Proc.new { |c| c.request.content_type == 'application/json' }
  
  before_action :authenticate

  attr_reader :current_user

  private

    def authenticate

      @current_user = AuthorizeApiRequest.call(request.headers).result
      render json: { error: 'Not Authorized' }, status: 401 unless @current_user

    end
    
end

AuthorizeApiRequest.call,Rails 抱怨说:

未初始化的常量 Api::ApiController::AuthorizeApiRequest

我的 AuthorizeApiRequest 类在 app/commands 下定义:

class AuthorizeApiRequest
  prepend SimpleCommand

  def initialize(headers = {})
    @headers = headers
  end

  def call
    user
  end

  private

  attr_reader :headers

  def user
    @user ||= User.find(decoded_auth_token[:user_id]) if decoded_auth_token
    @user || errors.add(:token, 'Invalid token') && nil
  end

  def decoded_auth_token
    @decoded_auth_token ||= JsonWebToken.decode(http_auth_header)
  end

  def http_auth_header
    if headers['Authorization'].present?
      return headers['Authorization'].split(' ').last
    else
      errors.add(:token, 'Missing token')
    end
    nil
  end
end

所以它似乎不允许我在没有在前面添加命名空间的情况下调用AuthorizeApiRequest.call。如何解决?

【问题讨论】:

  • 尝试使用::AuthorizeApiRequest.call

标签: ruby-on-rails


【解决方案1】:

您的 app/commands 文件夹在启动时似乎没有加载到 Rails 中。

您需要在您的自动加载路径中包含您的 app/commands 才能使其正常工作,或者在您的控制器中手动要求该文件。

见:https://guides.rubyonrails.org/autoloading_and_reloading_constants.html#autoload-paths

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-03-27
    • 2013-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-25
    • 2018-08-25
    • 1970-01-01
    相关资源
    最近更新 更多