Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Circular dependency detected while autoloading constant when loading constant

First of all: I googled and used the search here and found answers to the same error but on different setups. Maybe I broke sth different ;)

Error:

RuntimeError at /admin/users Circular dependency detected while autoloading constant Admin::UsersController 

The structure is:

App => controllers => admin => users_controller.rb 

Routes:

namespace :admin do   resources :stuff   resources :users end 

Users controller:

class UsersController < Admin::BaseController   def new     #code   end    def create     #code   end    def index     #code   end    private    def user_params    #code   end end 

Admin base controller

class Admin::BaseController < ApplicationController   layout 'admin'   before_filter :require_login end 

Using: Rails 4.1.4, Ruby 2.1.2 What did I do wrong here?

Thanks for your help!

Edit:

development.rb

Rails.application.configure do  config.cache_classes = false  config.eager_load = false  config.consider_all_requests_local       = true  config.action_controller.perform_caching = false  config.action_mailer.raise_delivery_errors = false  config.active_support.deprecation = :log  config.active_record.migration_error = :page_load  config.assets.debug = true  config.assets.raise_runtime_errors = true end 
like image 257
tomr Avatar asked Aug 23 '14 10:08

tomr


1 Answers

It looks like the primary issue may just be that you haven't namespaced your UsersController under the Admin namespace, here:

class UsersController < Admin::BaseController 

Simple fix:

class Admin::UsersController < Admin::BaseController 

However, I suggest that you also break out your namespaces out into distinct parts to save future headache. So instead of the above, do this:

# app/controllers/admin/users_controller.rb module Admin   class UsersController < Admin::BaseController     # ...   end end 

And do the same with all other namespaced controllers, such as:

# app/controllers/admin/base_controller.rb module Admin   class BaseController < ApplicationController     # ...   end end 

This way, as Rails is loading and autoloading and so forth it will always be sure to define the Admin module before attempting to load the classes under it. Sometimes you get unknown constant errors otherwise. The reasoning is a bit complex, but if you'd like to have a look check out this post.

UPDATE

On Rails Edge, there is now an official Guide on the topic of Auto Loading of Constants.

like image 98
pdobb Avatar answered Sep 25 '22 07:09

pdobb