Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails assign value to variable once per day

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?

like image 545
Choylton B. Higginbottom Avatar asked Feb 16 '26 23:02

Choylton B. Higginbottom


1 Answers

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
like image 52
meagar Avatar answered Feb 18 '26 19:02

meagar