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
So I used to have in Rails 2 something like this:
config.autoload_paths += Dir["#{config.root}/app/models/**/"]
And the following files:
class User::Base
class User::Admin
When I upgraded to Rails 3, I kept getting an error along these lines: Expected .../app/models/user/foo.rb to define Foo
. This clearly seemed crazy since Rails 2 automatically assumed that what you put in user/foo.rb would be User::Foo
not just Foo
.
So the way I ended up solving this was getting rid of model subdirectories in autoload_paths
and doing something like this:
I created app/models/user.rb with:
module User
autoload :User, 'user/base'
autoload :User, 'user/admin'
end
This worked for me in Rails 5.
Adding the following to application.rb
config.autoload_paths += Dir[ Rails.root.join('app/models/**/') ]
Beware though that you cannot have the same name on your folder as any of your models.
Until I find a better solution I've created a init.rb in the app/models folder:
app/models/init.rb
%w[blog].each do |folder|
path = [File.dirname(__FILE__), folder, "*.rb"].join('/')
Dir[path].each {|file| require file }
end
Servers the purpose until now.
Here is what I used for Rails 3:
config.autoload_paths += Dir[Rails.root.join('app', 'models', '{**}')]
This configuration tells Rails to scan all the app/models subfolders recursively and load all found models. No namespacing required.
We needed to do this, and there is a very simple way.
move your models into the sub-folders, and then tell rails to load files from all subfolders in your environment.rb file:
config.load_paths += Dir["#{RAILS_ROOT}/app/models/*"].find_all { |f| File.stat(f).directory? }
No namespacing required, and the models can be referred to as normal in your app
Maybe you could look upon RailsEngines. It's not exactly what you need, but could gave you some ideas.
Other than that, if your script seems to work fine (you could also just read all the files on each subfolder on model and require them), I don't see any problem against it.