问题
What is a right way to preload Rails model in development mode?
Background: Rails 2.2, memcahe as cache store.
When Rails start in production mode first of all it preload and cache all models. In development mode it use laizy loading. That's why wen we store any model into rails cache, for example, Rails.cache.write("key", User.find(0)) on next loadind of app, when we try do Rails.cache.read("key") memcache fire, that User is unknown class/module. What is a right way to preload class in this situation?
回答1:
You can get around this by doing something like this:
User if Rails.env == 'development'
@user = Rails.cache.fetch("key"){ User.find(0) }
This will force the User model to be re-loaded before the cache statement. If you have a class with multiple cache statements you can do this:
class SomeController
[User, Profile, Project, Blog, Post] if Rails.env == 'development'
def show
@user = Rails.cache.fetch("user/#{params[:user_id]") do
User.find(params[:user_id])
end
end
end
If you are in Rails 2.x and Rails.env does not work you can always use RAILS_ENV or ENV['RAILS_ENV'] instead. Of course, your other option is to simply disable caching in your development environment, then you don't have to deal with this issue at all.
来源:https://stackoverflow.com/questions/5013773/rails-preloading-class-in-development-mode