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 &&
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
.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With