0

I have a rails application where I am implementing caching using memcached and dalli.

I am storing results in hash like this

Rails.cache.write("home_stays[#{home_stay['id']}]", home_stay, expires_in: 5.minutes)

I can fetch value for a particular homestay using it's id.

What I am confused about is how can I get all homestays from the cache.

If I run Rails.cache.fetch("home_stays"), I get nil.

Is there a way to get all values of a cached hash in rails ?

update: As per Chakreshwar's suggestion I have added following in homestay model.

  def self.home_stay_cache
    Rails.cache.fetch("all_home_stays",expires_in: 5.minutes) do
      all
    end
  end

On running HomeStay.home_stay_cache I get following

Cache read: all_home_stays ({:expires_in=>300 seconds})
Cache generate: all_home_stays ({:expires_in=>300 seconds})
NameError: undefined local variable or method `all' for Homestay:class
RamanSM
  • 275
  • 3
  • 13

1 Answers1

0

Write the below in the model: I am assuming that you are in the HomeStay model

def self.home_stay_cache
    Rails.cache.fetch("all_home_stay", expires_in: 5.minutes) do
      all
    end
end

Then , you can fetch it like HomeStay.home_stay_cache

Chakreshwar Sharma
  • 2,571
  • 1
  • 11
  • 35