ruby-on-railsservice-object

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 in /services:

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

Error when calling MatchService from SearchHandlersController#match:

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

Solution

  • First of all, if you named the file MatchService.rb, you should change name of this file into match_service.rb.

    If this isn't work in your case, you can always call the service from the root by add :: before the service name like that: ::MatchService.call(@string).

    I hope it helps you!