Ask A Question

Notifications

You’re not receiving notifications from this thread.

Autoloading models not working

Giancarlo Corzo asked in Rails

Hi,

I have this model structure

/models
  /survey
       /questions
         question.rb
         survey.rb

I have used this autoloading in my application.rb so I don't have to deal with modules everytime I have create a folder in my models

config.autoload_paths += Dir[Rails.root.join('app', 'models', '**/')]

Normally I don't have any problem but this time I get an autoload issue:

Unable to autoload constant Survey::Question, expected /home/gian/repository/capitan/app/models/survey/question.rb to define it

I'm using STI in the question.rb model so I can have several models with custom code in it.

When I access each model I don't have any problem but when I try to do this

@survey = Survey.find(1)
@survey.questions 

This are my model definitions:

class Survey < ActiveRecord::Base
  has_many :questions
  validates :name, :presence => true
end

class Question < ActiveRecord::Base
  belongs_to :survey, :inverse_of => :questions
  has_many :answers

  has_and_belongs_to_many :sprint_users

  default_scope { order(:position) }

  validates :survey, :question_text, :presence => true

end

class TeacherSprint < Question
end

From what I can tell from the error message it's expecting that the question is inside a module but I don't get this kind of error in any other model so it's strange.

If you want to check the code you can access the code on github because it's an open source code.

github.com/Laboratoria/capitan

Reply

I fixed it, the problem was related to the name of the folders for some reason I had to change from

/models/survey/
to
/models/surveys

Reply

Ah glad you got that fixed. I was going to reply yesterday and got distracted. I figured that there was something up with the folder naming and the naming of the classes. Rails always expects you to have those names match up which the error tries to tell you, but it can never point out the exact problem.

Usually when you see the error like "Unable to autoload constant Survey::Question, expected /home/gian/repository/capitan/app/models/survey/question.rb to define it" then you know you've made a typo or forgot a module name somewhere.

Glad it's working! 🤘

Reply
Join the discussion
Create an account Log in

Want to stay up-to-date with Ruby on Rails?

Join 86,946+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.