Sub directories for STI models in Rails

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

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!


Entry filed under: Uncategorized. Tags: .

Code Comments are not for tracking changes Launch an App Month – Simple WorkFlow task manager

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

Trackback this post  |  Subscribe to the comments via RSS Feed


%d bloggers like this: