Search code examples
ruby-on-railsruby-on-rails-4rubygemsruby-on-rails-5rails-engines

LoadError Unable to autoload constant ( Rails Engine )


Whenever i hit the endpoints (example: greet ) exposed by rails engine i receive this error.

Error:

"LoadError(Unable to autoload constant TestingController, 
expected /local_path/app/controllers/testing_controller.rb to define it): 
/Users/xxxxx/.rvm/gems/ruby-2.5.1/gems/activesupport-5.2.1/lib/active_support/
dependencies.rb:507:in `load_missing_constant'"

Engine:

I have an engine with action method greet defined as below

# type: class
# path: app/controllers/testing_controller.rb
# file name: testing_controller.rb 
module Parent
  module Child
    class TestingController < ApplicationController
      def initialize
        @name = 'BOB'
      end

      def greet
        render json: {'hi': 'hi', 'name': @name}
      end
    end
  end
end

routes defined as

# type: route
# path: app/config/routes.rb
# file name: routes.rb 
Parent::Child::Engine.routes.draw do
  get 'greet', to: 'testing#greet', as: :greet
end

Details:

This engine has been mounted to a gem ABC which is then used in the rails app called Example. When i hit the greet route in the app via http://localhost:3000/greet for the first time i receive LoadError.

However if i refresh the page it renders the json as expected. {"hi":"hi","name":"BOB"}.

we have development.rb (app/config/env/) has cache and eager load defined as below

config.cache_classes = false
config.eager_load = false

Ruby: 2.5.1
Rails: 5.2.1

Thanks for your help, much appreciated.


Solution

  • The message seems to be coming from the expectation that in the root level of the file testing_controller.rb has a definition of a TestingController class whilst you have that class defined nested within Parent::Child:: modules.

    I guess that if you put your testing_controller.rb file in the following path: app/controllers/parent/child/testing_controller.rb the error will disappear.