Ryan Twomey
Namespacing models in Rails 3 using autoload_paths

When working in a Rails app with lots of models, I’m often tempted to clean things up by namespacing.  A project I’m currently working on has some 54 models and that number will only increase.

The problem with namespacing is that it introduces a lot of additional ugliness in the models.  You have to change the class names and include :class_name attributes in order to find all associations.

A better way seemed to be using Rails 3’s autoload_paths.  For instance, if I organized my models into a bunch of subdirectories, then I could do something like the following in my environment.rb file:

config.autoload_paths += %W("#{Rails.root}/app/models/**/**")

This works great when in the production environment, but not in development.  Whenever loading an association, I would get something along the lines of “Expected … to define …”.  I suspect the issue is Rails reloading models on-demand, and getting confused.  In production, all the models are loaded once.

I don’t have a solution yet, unfortunately.