: counter_cache => true to store the amount

I have a users and scores table. Here are the associations:

 belongs_to :user #score model has_many :scores #user model 

The users table has a column called scores_count . In this column, I store the sum of all the values ​​in the scores table.

I wanted to use this method to store the sum of all scores in the scores_count: :counter_cache => true column scores_count: :counter_cache => true

But :counter_cache => true saving only the number of rows in the scores table. Is there any similar method for storing the sum of all values ​​from a scores table? Or should I implement this task myself?

+4
source share
2 answers

Not. You will have to implement it yourself. Counter-cache is designed to store only the number of related records. You can implement it with a callback on Score to update the associated User . See Also How to cache a computed column in rails?

Also, if you have no noticeable performance issues when adding up each time, avoid using a cache like this. It is simply that which can easily go wrong and become obsolete. It's not worth it if you really don't need it.

+4
source

You can use counter_culture gem.

 class Score < ActiveRecord::Base belongs_to :user counter_culture :user, column_name: 'scores_sum', delta_column: 'score_value' end 
+5
source

All Articles