Unable to autoload constant API Controller in Rails 4

nulltek picture nulltek · May 8, 2016 · Viewed 9.1k times · Source

I'm creating a simple api endpoint in my Rails 4.2.6 app but am having problems with it.

When I hit the url: http://lvh.me:9077/api/v1/grubs I receive the following error:

Unable to autoload constant Api::V1::GrubsController, expected /Users/shakycode/code/grubs/app/controllers/api/v1/grubs_controller.rb to define it

Here is my routes.rb file defining the endpoint.

namespace :api do
    namespace :v1 do
      resources :grubs, only: [:index]
    end
  end

Here is my app/controllers/api/v1/grubs_controller.rb

class API::V1::GrubsController < ApplicationController
   protect_from_forgery with: :null_session
   before_action :destroy_session

 def destroy_session
   request.session_options[:skip] = true
 end

  def index
    @grubs = Grub.all
    respond_to do |format|
      format.json { render json: @grubs}
    end
  end
end

I have a Rails 4.2.1 app where I used the same strategy, but in 4.2.6 I'm having this error occur when I try to pull against the API.

Thanks in advance!

Update: Here's the exception that is raised using better_errors in the browser:

load_missing_constantactivesupport (4.2.6) lib/active_support/dependencies.rb
490
491
492
493
494
495
496
497
498
499
500
        if loading.include?(expanded)
          raise "Circular dependency detected while autoloading constant #{qualified_name}"
        else
          require_or_load(expanded, qualified_name)
          raise LoadError, "Unable to autoload constant #{qualified_name}, expected #{file_path} to define it" unless from_mod.const_defined?(const_name, false)
          return from_mod.const_get(const_name)
        end
      elsif mod = autoload_module!(from_mod, const_name, qualified_name, path_suffix)
        return mod
      elsif (parent = from_mod.parent) && parent != from_mod &&

Answer

Anthony E picture Anthony E · May 8, 2016

Rails typically only capitalizes the first name of a module. In other words, Rails expects the namespace Api::V1::GrubsController, but you're defining it as API::V1::GrubsController.