简体   繁体   中英

Rails.cache.clear fails with undefined method `clear' for nil:NilClass when running in a rake task

Upon following the instructions to create a rake task to clear the cache, when running that rake task:

namespace :cache do
  desc "Clears Rails cache"
  task :clear do
    Rails.cache.clear
  end
end

and running that rake task with:

rake cache:clear

I get an error:

undefined method `clear' for nil:NilClass

When running Rails.cache.clear from the rails console, it successfully clears the cache without an error. Why is cache nil on the Rails object in the rake task, but not in the rails console?

Note: I am using dalli and memcache.

To answer Why is => :environment needed?

:environment is a task defined by rails. When you need to interact with your application models, perform database queries and so on, your custom task should depend on the environment task, as it will load your rails application code.

Rails.cache will return nil if your application is not loaded. Hence, the error undefined method 'clear' for nil:NilClass

You need to run environment task before your custom clear task.

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

Figured it out. I was missing => :environment after :clear

The below works:

namespace :cache do
  desc "Clears Rails cache"
  task :clear => :environment do
    Rails.cache.clear
  end
end

Why is => :environment needed?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM