Rails:未初始化的常量 - 无法从控制器访问另一个 class

Rails: Uninitialized constant - can not access to another class from controller

search_handlers_controller.rb

class SearchHandlersController < ApplicationController
  def match 
    @string = 'string'        
    @result = case params['search_style']
    when 'match'
      MatchService.call(@string)    
      ...     

MatchService.rb 在 /services:

# frozen_string_literal: true
class MatchService < ApplicationService
  ...
  def call(string)
    'Match'
  end
end

从 SearchHandlersController 调用 MatchService 时出错#match:

NameError (uninitialized constant SearchHandlersController::MatchService):
app/controllers/search_handlers_controller.rb:18:in `match'

首先,如果您将文件命名为MatchService.rb,则应将此文件的名称更改为match_service.rb

如果这在您的情况下不起作用,您始终可以通过在服务名称前添加 :: 从根调用服务,例如:::MatchService.call(@string).

希望对您有所帮助!