Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

:counter_cache => true for storing sum

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

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

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

I wanted to use this way for storing the sum of all scores in the column scores_count: :counter_cache => true

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

like image 792
user984621 Avatar asked Jun 13 '12 16:06

user984621


1 Answers

You could use counter_culture gem.

class Score < ActiveRecord::Base
  belongs_to :user
  counter_culture :user, column_name: 'scores_sum', delta_column: 'score_value'
end
like image 171
denis.peplin Avatar answered Sep 29 '22 16:09

denis.peplin