Autoloading models not working
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
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
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! 🤘