how to write a partial into a cache from a back ground process and read the partial from the cache and render it in rails? [closed]
Want to improve this question? Add details and clarify the problem by editing this post.
开发者_开发问答Closed 2 years ago.
Improve this questionRelated to the question i have asked previously How to store a database intensive page into cache from a background process in rails
i want to write a partial into cache from a background process every 15 mins. And when ever a user request comes in i can just read the partial from the cache and render it and never explicitly expiring it.
Is there any ways to actually do it?
Thanks,
I think what you want is to read the results of the db query with:
Rails.cache.fetch("key", :expires => 365.days) do
# db query
end
and update it from a cron job 15 minutely with:
Rails.cache.write("key",
# db query
)
Then allow your partial to regenerate every 15 minutes as well (or every time even), since that's not the intensive part of the operation.
N.B.
- I'm setting :expires => 365.days in case you have a default expiry time set in your config and because I haven't looked up how to explicitly say 'never'.
- You need the query in the fetch block rather than just doing a read call so things don't break when the cron job has never been run, i.e. after a reboot. That is users will still be stuck waiting for it to load the first time the page gets hit after reboot/restart.
精彩评论