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

◇◆丶佛笑我妖孽 提交于 2019-12-07 18:19:56

问题


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.


回答1:


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.




回答2:


I believe this can be solved by adding require_dependency 'vehicle' in the controller.




回答3:


Using rails 3.0.3 and passenger 3, I don't see this at all. If updating your app to 3.0.3 doesn't fix it, I'd move off of WEBrick.

I personally recommend using something other than WEBrick anyway. Passenger has been my server of choice for development + production for quite a while now.



来源:https://stackoverflow.com/questions/4609656/how-to-make-rails-3-reload-sti-classes-in-development-mode

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!