Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to autoload constant API Controller in Rails 4

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 &&
like image 978
nulltek Avatar asked May 08 '16 18:05

nulltek


2 Answers

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.

like image 100
Anthony E Avatar answered Sep 23 '22 00:09

Anthony E


I had a similar issue when working on a rails 6 application.

The issue was that I defined my controller as usual

class ProductsController < ApplicationController
  def index
end

Meanwhile, I had added versioning to be APIs which resulted in a namespace of this kind Api/V1.

Here's how I solved it:

I simply had to add the namespace to the controller class definition.

class Api::V1::ProductsController < ApplicationController
  def index
end

That's all.

I hope this helps

like image 42
Promise Preston Avatar answered Sep 24 '22 00:09

Promise Preston