2012-10-15 43 views
1

在我的lib/tasks文件夾中,我添加了一個新的.rake文件。如何將模型導入到自定義Rake任務?

在rake任務,我這樣做:

p = Post.new(....) 
p.save! 

當我跑我的任務,我得到的錯誤:

rake aborted! 
uninitialized constant Post 

我有什麼做的導入我的Post模型?

回答

5

我在想你可能會錯過環境聲明。爲了讓Rake瞭解您的Rails環境,這是必需的。你的耙子任務應該看起來像這樣:

task :my_rake_task => [:environment] do 

    # Your code here 

end 

讓我知道是否解決了問題!

4

您想讓任務依賴於rails環境。您可以通過在任務聲明後指定=>:環境來這樣做:

namespace :my_task do 
    desc "an example task" 
    task :create_post => :environment do 
    Post.new .... # the rest of the implementation 
    end 
end