2010-11-29 58 views
26

我的簡單rake任務存儲在lib/tasks/items_spider.rake中,運行良好。它的全部功能是在Item型號上撥打spider!Rails 3 rake任務在生產中找不到型號

namespace :items do 
    desc "Spider the web for data, hoorah" 
    task :spider => :environment do 
    Item.spider! 
    end 
end 

我有:environment任務作爲依賴,所以一切都工作得很好。然而,當我加RAILS_ENV=production,我打的錯誤,無論是我的本地服務器和生產服務器上:

$ rake items:spider RAILS_ENV=production --trace 
(in /home/matchu/Websites/my-rails-app) 
** Invoke items:spider (first_time) 
** Invoke environment (first_time) 
** Execute environment 
** Execute items:spider 
rake aborted! 
uninitialized constant Object::Item 
/home/matchu/.rvm/gems/[email protected]/gems/rake-0.8.7/lib/rake.rb:2503:in `const_missing' 
/home/matchu/.rvm/gems/[email protected]/gems/rspec-core-2.0.0.beta.22/lib/rspec/core/backward_compatibility.rb:20:in `const_missing' 
/home/matchu/.rvm/gems/[email protected]/gems/rspec-expectations-2.0.0.beta.22/lib/rspec/expectations/backward_compatibility.rb:6:in `const_missing' 
/home/matchu/Websites/openneo-impress-items/lib/tasks/items_spider.rake:4:in `block (2 levels) in <top (required)>' 
/home/matchu/.rvm/gems/[email protected]/gems/rake-0.8.7/lib/rake.rb:636:in `call' 
[...trace of how rake gets to my task...] 

這似乎只是奇怪了吧。顯然這些模型尚未正確加載。我使用的是Rails 3.0.3,但是當Rails 3處於測試階段時,此應用程序的開發就開始了。我如何去調試這個問題?謝謝!

+0

這裏到達了一下(注意!這應該config.threadsafe呼叫後加入),但你有沒有嘗試過的RAILS_ENV聲明移動到命令的開始? – 2010-11-29 02:09:55

+0

@Peer:no go :(謝謝! – Matchu 2010-11-29 02:16:34

+0

「Item」模型在哪裏?通常的位置? – 2010-11-29 03:02:35

回答

43

與在生產環境中運行應用程序相反,Rake任務確實不會急於加載您的整個代碼庫。你可以看到它在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 

所以只有如果$rails_rake_taskfalse,將應用急於裝生產。並且$rails_rake_task:environment Rake任務中設置爲true

最簡單的解決方法是簡單地require您需要的模型。不過,如果你真的需要的所有應用程序在Rake任務被加載,這是很簡單的加載:

Rails.application.eager_load! 

的原因都在發展這項工作是因爲Rails的自動加載自己的模型開發模式。這也可以在Rake任務中使用。

37

在您的環境/ production.rb,您應該添加以下內容:

config.dependency_loading = true if $rails_rake_task 

它解決了這個問題對我來說。

相關問題