Reputation: 101
I am still a beginner concerning ruby on rails and I am trying to create a simple API but I am facing this error :"uninitialized constant Api"
ideas_controller.rb
module Api
module V1
class ItemsController < BaseController
def index
@ideas = Idea.all
render json: @ideas
end
end
end
end
routes.db
Rails.application.routes.draw do
namespace :api do
namespace :v1 do
resources :ideas
end
end
end
application_controller.rb
class ApplicationController < ActionController
protect_from_forgery with: :null_session
end
base_controller.rb
module Api
module V1
class BaseController < ApplicationController
respond_to :json
end
end
The project's directories:
I have also tried this approach and changed the project's structure to :
Also, I have enabled : config.eager_load = true After that I got the following error:
`block in load_missing_constant': uninitialized constant Api::V1::BaseController (NameError)
Upvotes: 6
Views: 13494
Reputation: 286
Try this in your ideas controller
module Api
module V1
class IdeasController < Api::V1::BaseController
def index
@ideas = Idea.all
render json: @ideas
end
end
end
end
And define your base controller in the following way
class Api::V1::BaseController < ApplicationController
respond_to :json
end
Upvotes: 0
Reputation: 461
If you're in the development environment, eager loading is turned off by default, which can be fixed by turning on eager load (change to config.eager_load = true
in config/development.rb
). Eager loading will allow the whole Rails app to be loaded when the server starts (which is slightly slower), but will fix your problem since that file will be loaded.
Upvotes: 3
Reputation: 584
This error because module Api
is not defined before, I guess if you made like this it gonna work. from an answer here
module Api
module V1
class IdeasController < ApplicationController
def index
@ideas = Idea.all
render json: @ideas
end
end
end
end
another solution could be like this:
module Api
module V1
end
end
class Api::V1::IdeasController < ApplicationController
def index
@ideas = Idea.all
render json: @ideas
end
end
hope it helps.
Upvotes: 0