Rails console: Unable to autoload constant

56,527

Solution 1

It seems like a case of messed up naming convention.

As per Rails naming convention, file names should be in snake_case and class names in CamelCase. In your scenario, the file name should be customer_rating.rb and class name should be CustomerRating.

After making these changes, use CustomerRating.all(as the updated class name is CustomerRating) to fetch all the customer ratings. Do not use Customer_rating.all.

Solution 2

I'd also like to add a scenario of this problem that I found for future reference.

I'm running Rails 4.0 and I had this same problem but what happened was I had a model named Student inside student.rb that was contained in a folder called Student. I didn't realize it at first but the folder name was the problem. Changing the folder name to something other than a model name solved the problem.

Solution 3

If the naming convention is not off, like in this question, it may be an issue on initial first load if you're making a lot of requests at the same time. I experienced this with nested controllers Api::LocationsController.

I solved it by enabled eager_load in development env:

Rails.application.configure do
  ...
  # Enabled this to avoid crash unable to autoload controller 
  # Error happens when you start and stop server on initial requests
  # solution found via https://github.com/rails/rails/issues/32082#issuecomment-367715194
  config.eager_load = true

I based this off of rails issues comments: https://github.com/rails/rails/issues/32082#issuecomment-367715194

Share:
56,527
dmt2989
Author by

dmt2989

Updated on April 02, 2021

Comments

  • dmt2989
    dmt2989 about 3 years

    I have a Customer_ratings model that allows users to leave feedback on each other. The web app is working properly, and feedback is collected, stored and displayed.

    I wanted to go in and delete some feedback through the rails console, but when I enter Customer_rating.all, I get the following error:

    LoadError: Unable to autoload constant Customer_rating, expected /Users/myapps/app/models/customer_rating.rb to define it
    

    Similarly, if I enter Customer_rating[0], I get:

    RuntimeError: Circular dependency detected while autoloading constant Customer_rating
    

    I don't have this issue while accessing other tables through my console.

    What could be causing the issue, and why wouldn't this error prohibit Customer_ratings from working properly through the web app?