Khallil Mangalji
Khallil Mangalji

Reputation: 481

Rails.cache.fetch not caching object

Hi I have a User model which

has_many :devices
has_many :events, :through => :devices.

This has the following method:

def get_events_for_devices limit=nil
  events.limit limit
end

Then I have a controller for users which I need to cache 500 events for each users device. Currently I am using the following call

user_requested = User.find(params[:id])

  profile_info = Rails.cache.fetch("#{user_requested.email}-profile-info") do 
    {:user => user_requested, :devices => user_requested.devices, :events => user_requested.get_events_for_devices(500)}

I am able to get back the :user and :devices from the cache, but not the :events - they just dont seem to be there.

However, I am able to get the events if I don't use the Rails.cache, and simply call user_requested[:events].

Any ideas on how I should proceed? Thanks!!

Upvotes: 1

Views: 2944

Answers (1)

Salil
Salil

Reputation: 9722

How fetch works is if you don't have associated data with a given key, it will execute the block. Since you do have some data for "#{user_requested.email}-profile-info" key, the block is not executed. I think if you want it to recalculate events data if events key is not there, you should have 3 different fetch blocks for 3 different types of keys like this:

profile_key = "#{user_requested.email}-profile-info"
user_profile_data = Rails.cache.fetch("#{profile_key}:user") { user_requested }
device_profile_data = Rails.cache.fetch("#{profile_key}:devices") { user_requested.devices }
events_profile_data = Rails.cache.fetch("#{profile_key}:events") { user_requested.get_events_for_devices(500) }

Upvotes: 4

Related Questions