Search code examples
ruby-on-railsrubysingle-table-inheritance

How to make Rails 3 reload STI classes in development mode?


After switching to Rails 3, I noticed that I have to reboot my server to make STI model classes reload with each request. For example, suppose I have this:

# app/models/vehicle.rb
class Vehicle < ActiveRecord::Base
end

# app/models/car.rb
class Car < Vehicle
end

If I make a change to Vehicle, the change is loaded on the next request. But if I make a change to Car, I have to reboot my server for it to load.

Any ideas on fixing this?

I'm running WEBrick, but I'm not committed to it.


Solution

  • We found that we needed both zetetic's solution and some additional code to make this work (at least in Rails 3.0.9). For the above problem, the solution would look something like:

    In config/environments/development.rb:

      config.after_initialize do
        ["vehicle"].each do|dep|
          require_dependency( (Rails.root + "app/models/#{dep}").to_s )
        end
      end
    

    In app/controllers/application_controller.rb:

    class ApplicationController < ActionController::Base
      if Rails.env == 'development'
        require_dependency( (Rails.root + "app/models/vehicle").to_s )
      end
    ...
    

    The code in development.rb handles the initial loading of the class, and the code in ApplicationController handles subsequent requests.