I have a database that gets updated once per day. Rather than querying it in my controller every time a user makes a request, e.g.:
@rainy = Place.where("forecast = 'rain'")
Can I run that query just once per day, after the DB update, and make the values available in a variable that my controller can access?
You can, but that isn't really a good solution. Rails already has a way of persisting the result of expensive computations across requests: Caching.
Use
@rainy = Rails.cache.fetch(:rainy, expires_in: 1.day) do
Place.where(forecast: 'rain')
end
If you need the value to expire at a specific time each day, you can define a rake task which computes the value, and then expires the cache:
# lib/tasks/rainy.rake
task :compute_rainy
# ... whatever comutation produces your database value ...
# Then, expire the cache for :rainy so that the next
# request loads (and caches) the new value
Rails.cache.delete(:rainy)
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With