Reputation: 311
I am caching an external API response into Rails. I read from the cache and it returns nil as expected. I store into the cache it returns true, I read again and it returns my value, but if I make another request from the client with the same parameters it returns nil as if the value was not stored.
def create
cache = ActiveSupport::Cache::MemoryStore.new
url = "http://api.openweathermap.org/data/2.5/weather?zip=" + params[:zip] +"&units=imperial&APPID=4e66533961b500086bf6bd7c37d4b847"
@weather = fetch_weather(url)
p cache.read(params[:zip])
weather = cache.read(params[:zip])
p weather
p weather.nil?
if weather.nil?
cache.write(params[:zip],@weather,:expires_in => 30.minutes)
end
p cache.read(params[:zip])
render json: @weather
end
So for example I will use a zip code 94016 for the first time and it will return
nil
nil
true
<RestClient::Response 200 "{\"coord\":{\"...">
I will run it again with the same zip code and get the same response. I have enabled caching in my development environment. I am not sure why its not working. Thank You.
Upvotes: 3
Views: 2175
Reputation: 736
Since every time you request this action you create a cache store:
cache = ActiveSupport::Cache::MemoryStore.new
you should put this line in your config file:
config.cache_store = :memory_store, { size: 64.megabytes }
then use Rails.cache to get or set a cache.
Upvotes: 3