[英]Rails.cache.clear fails with undefined method `clear' for nil:NilClass when running in a rake task
在按照說明執行創建rake任務以清除高速緩存時,運行該rake任務時:
namespace :cache do
desc "Clears Rails cache"
task :clear do
Rails.cache.clear
end
end
並使用以下命令運行該rake任務:
rake cache:clear
我收到一個錯誤:
undefined method `clear' for nil:NilClass
從rails控制台運行Rails.cache.clear時,它會成功清除緩存,而不會出現錯誤。 為什么在rake任務中,Rails對象上的緩存為nil,而不是在Rails控制台中?
注意:我正在使用dalli和memcache。
回答為什么需要=>:environment?
:environment
是由rails定義的任務。 當您需要與應用程序模型進行交互,執行數據庫查詢等時,您的自定義任務應取決於environment
任務,因為它將加載您的rails應用程序代碼。
如果您的應用程序未加載, Rails.cache
將返回nil。 因此, undefined method 'clear' for nil:NilClass
的錯誤undefined method 'clear' for nil:NilClass
您需要先運行environment
任務,然后再執行自定義clear
任務。
namespace :cache do
desc "Clears Rails cache"
task :clear => :environment do ## This will run environment task first and then clear task
Rails.cache.clear
end
end
弄清楚了。 我錯過了=>:環境在:clear之后
下面的作品:
namespace :cache do
desc "Clears Rails cache"
task :clear => :environment do
Rails.cache.clear
end
end
為什么需要=>:environment?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.