views:

27

answers:

1

I'm trying to create something similar to the stackoverflow "user score" on my site with a mysql. I don't want to be calculating this score every time a user is accessed because multiple user scores will be displayed at the same time and the way it's calculated doesn't require it to be updated frequently. My thoughts are to update all of the score rows in the user table on a timed basis (hourly, daily, etc.) Here is what it would look like:

user.score = user.score + x_actions_since_last_update *2 + y_actions_since_last_update - z_actions_since_last_update*3

But how do I go about running this at a timed interval? Is this even the best method to get done what I'm trying to do? Is there some sort of caching I should do instead? Thank you!

+2  A: 

Instead of calculating the score at given intervals, you could update the score for a user whenever the user performs an action affecting the total score.

Using your example, whenever a user performs action X, add 2 to the user's score. For action Y, add 1 to the score, and for action Z subtract 3.

If you don't want to update the score at every action, you could write a Rake task that updates the score; have a look at this tutorial for an introduction to using Rake with Rails. If you're deploying your application on a unix-like OS, run the task at regular intervals using cron.

Pär Wieslander
Great! The only thing is that I do not want to reward a user immediately, because the way "x_action" works is that they are signing up for an event which will take place in the future and I only want to update their score once the event time has *passed*. I would much rather use your first option if there is a way to do it like this...
Jack
Ok, that's a perfectly valid reason not to update the score immediately. In that case, writing a small rake task that updates the score and adding a cron job that runs the task on regular intervals is probably the way to go.
Pär Wieslander