Rails - how to run method only first time, when user come to my page
-
01-06-2021 - |
Question
I have lots of data in database and I wanna make a statistics from them. Lots of data = thousands rows in table, and I wanna get the daily, weekly, monthly (for every month) stats... just detailed statistics.
The problem is, that the getting these data takes a time (and not little).
So, I think what would be the fastest, clearest and just most effective way to get it...
My first idea - when the user come to my app, in the ApplicationController
method I'll fetch from DB stats, save the objects I got into the session's variable and then I will use these variables as a source. Then when I would need somewhere in the app print out the stats, I just use this loaded data.
The question is: is this a good idea? Or, exist any better way?
Solution
Instead of storing DB stats in session variable. You can store in memcached
Rails has excellent built-in support for caching
OTHER TIPS
Another approach. You can cache parts of pages in per-user basis this way:
- cache [@user, :stat] do # or [@user, :stat, :daily]
statistic for the user @user
If some user's associated records affect his statistic then use:
# SomeModel.rb
belongs_to :user, touch: true
This way your user's updated_at
will be updated when related model's objects are changed and user's cache will be automatically treated as outdated and block inside - cache ... do
will be executed. Make sure that no (or minimum) db hits occur outside this block (e.g.: do not use Model1.where(conditions).all in your controller -- this way you will be making no db-requests, just constructing them).
To enable caching in development mode go to your config/environments/development.rb
and change to true
parameter config.action_controller.perform_caching
and restart your app.