Take the 2-minute tour ×

I have two models - Score & Weight.

Each of these models have about 5 attributes.

I need to be able to create a weighted_score for my User, which is basically the product of Score.attribute_A * Weight.attribute_A, Score.attribute_B * Weight.attribute_B, etc.

Am I better off creating a 3rd model - say Weighted_Score, where I store the product value for each attribute in a row with the user_id and then query that table whenever I need a particular weighted_score (e.g. my_user.weighted_score.attribute_A) or am I better off just doing the calculations on the fly every time?

I am asking from an efficiency stand-point.


share|improve this question
add comment

2 Answers

up vote 1 down vote accepted

I think the answer is very situation-dependent. Creating a 3rd table may be a good idea if the calculation is very expensive, you don't want to bog down the rest of the system and it's ok for you to respond to the user right away with a message saying that calculation will occur in the future. In that case, you can offload the processing into a background worker and create an instance of the 3rd model asynchronously. Additionally, you should de-normalize the table so that you can access it directly without having to lookup the Weight/Score records.

Some other ideas:

  1. Focus optimizations on the model that has many records. If Weight, for instance, will only have 100 records, but Score could have infinite, then load Weight into memory and focus all your effort on optimizing the Score queries.
  2. Use memoization on the calc methods
  3. Use caching on the most expensive actions/methods. if you don't care too much about how frequently the values update, you can explicitly sweep the cache nightly or something.
share|improve this answer
Thanks for the link on de-normalization. That's exactly what I am going to do. I just added a weighted_score attribute to my User model so that I am able to easily get the score I know my user needs. Then just update that periodically in the background like you suggest. –  marcamillion Oct 8 '12 at 23:59
let me know how it goes! –  Matt Dressel Oct 9 '12 at 0:18
add comment

Unless there is a need to store the calculated score (lets say that it changes and you want to preserve the changes to it) i dont see any benefit of adding complexity to store it in a separate table.

share|improve this answer
I am tempted to agree with you. –  marcamillion Oct 8 '12 at 23:39
add comment

Your Answer


