I have numerous models in my app/models folder. I\'d like to clean this folder up a little bit. Move models that belong to each other in subfolders. The problem is that by c
All the above answers didn't work for me. Somehow 'models' folder was loaded with subfolders, which resulted in 'Expected to contain ::.
Most of my subdirs were STI classes so I've moved them to app/models_sti//*. Then all I needed to do was to put in application.rb
#config.autoload_paths += Dir["#{Rails.root.to_s}/app/models/**/"]
# Loaded dynamically (cache_classes == false ?)
config.autoload_paths << Rails.root.join('app', 'models').to_s
config.autoload_paths += Dir["#{Rails.root.to_s}/app/models_sti/*"].find_all { |f| File.stat(f).directory? }
# Eager_load_paths - used only when cache_classes == true [rails spec says so]
config.eager_load_paths.delete_if do |path|
# If I didn't delete it from eager_load_paths I got errors even in develop
path == Rails.root.join('app', 'models_sti').to_s
end
config.eager_load_paths += config.autoload_paths
I also created subfolders, and then added the following to the application.rb file:
config.autoload_paths += Dir["#{config.root}/app/models/**/"]
But doing this alone isn't enough when subfolders are named using the same name as a model (e.g., a folder 'user' containing several files, one of which is 'user'). This was causing all kinds of errors in my code until I found that it could be solved by simply giving the folders names that are different from the models (e.g., 'user models') they contain. I found the suggestion at http://www.williambharding.com/blog/technology/rails-3-autoload-modules-and-classes-in-production/, which actually points to this question.
this version of Tilendor's solution works with Rails 3
config.load_paths and RAILS_ROOT are deprecated in Rails 3, also you should put it in the config block of the config/application.rb, not environment.rb
config.autoload_paths += Dir["#{Rails.root.to_s}/app/models/*"].find_all { |f| File.stat(f).directory? }
In my Rails 3.2.3 app, after i moved some models to subdirectories, i have stumbled into errors like
Expected /.../.../app/models/project/project_category.rb to define Project::ProjectCategory
for association calls (example: Project.first.project_category).
In the end, the workaround i found was to set :class_name for every association to model in subdirectory...
class Project < ActiveRecord::Base
belongs_to :project_category, :class_name => "::ProjectCategory"
end
"::" part here points to Rails that ProjectCategory model has no namespace, despite the fact that is defined in a 'models/project' subdirectory.