Rails 3 rake task can't find model in production

Contrary to running your application in production, a Rake task does not eager load your entire code base. You can see it in the source:

module Rails
  class Application
    module Finisher
      # ...
      initializer :eager_load! do
        if config.cache_classes && !$rails_rake_task
          ActiveSupport.run_load_hooks(:before_eager_load, self)
          eager_load!
        end
      end
      # ...
    end
  end
end

So only if $rails_rake_task is false, will the application be eager-loaded in production. And $rails_rake_task is set to true in the :environment Rake task.

The easiest workaround is to simply require the model that you need. However, if you really need all of your application to be loaded in the Rake task, it is quite simple to load it:

Rails.application.eager_load!

The reason all of this work in development is because Rails autoloads your models in development mode. This also works from within a Rake task.


In your environment/production.rb, you should add the following:

config.dependency_loading = true if $rails_rake_task

It solved the problem for me.

(Note: this should be added AFTER the config.threadsafe! call)