Archive for April, 2009

Sub directories for STI models in Rails

I recently started using Single Table Interitance in my Rails application and immediately wanted to group all the child models in a sub directory inside the models directory.

All over the web, the advice was just create a directory, stick your models in there and then add on of the following into environment.rb:


config.load_paths += Dir["#{RAILS_ROOT}/app/models/**/**]
# or
config.load_paths += Dir["#{RAILS_ROOT}/app/models/mysubdir"]

Well, this doesn’t seem to work, as of Rails 2.3.2 anyway (no idea about earlier versions).

It seems that Rails scans the models directory, and when it finds subdirectories in it, it loads the classes into a namespace that is the subdirectory name. If you have a subdirectory called Actions, your classes will end up loaded as Actions::SubClass, which is not want I wanted.

To get this working, I had to put the extra load path I wanted at the front of the load path array (at least before it loads the models directory):


config.load_paths.unshift "#{RAILS_ROOT}/app/models/**/**"
# or
config.load_paths.unshift "#{RAILS_ROOT}/app/models/mysubdir"

I am not really happy with this approach, but I have already wasted hours trying to get it working at all, so the hack will have to do for now!

April 10, 2009 at 6:02 pm Leave a comment


Feeds