Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails.cache.clear returns nil

I have this setup config.cache_store = :redis_store, ENV['REDIS_CACHE_URL']

$ redis-cli
127.0.0.1:6379> set random_key 1
OK

Now I go to the console and do Rails.cache.clear which returns nil

And I am still able to access the key random_key in the redis-cli. It did not clear the cache.

I could not read what Rails.cache returns here too ruby/2.3.4/lib/ruby/gems/2.3.0/gems/railties-4.2.8/lib/rails.rb

Is Rails.cache.clear is supposed to return true?

Can someone please help me out if my understanding is wrong?

like image 998
gates Avatar asked Oct 20 '25 13:10

gates


2 Answers

redis-cache stores data under a particular namespace.

For example, if you've configured redis-store according to Documentation, then cache keys will be stored under cache namespace. That means, that when you Rails.cache.write("random_key", "key") a key cache:random_key will appear in the Redis. Therefore, when you Rails.cache.clear, only keys under cache namespace will be deleted.

Hence, if you manually create random_key in Redis, Rails.cache.clear won't remove it. But if you manually create cache:random_key, it will.

like image 93
Igor Drozdov Avatar answered Oct 22 '25 04:10

Igor Drozdov


Be careful when using Rails.cache.clear it will invalidate all the keys for the application (source)

[~Not sure if this is the best place for this answer~]

This helpful article was a great way for me to understand caching when changing versions of Rails from 5.1+ to Rails 6.1+. The article talks about options for generating a cache key with or without versioning.

In the instance of my application, versioning was needed but not turned on when upgraded to Rails 6.1:

#in application.rb
config.active_record.collection_cache_versioning = true

Then within the application code where object.cache_key is called, I had to change it to object.cache_key_with_version (source)

like image 39
Jeff Spicoli Avatar answered Oct 22 '25 03:10

Jeff Spicoli



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!