: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?

Answers


No. You'll have to implement it yourself. Counter-cache is for storing the number of associated records only. You could implement it using a callback on Score to update the associated User. See also How can I cache a calculated column in rails?

Further, unless you have noticeable performance issues with summing each time, avoid using a cache like this. It's just something that can easily go wrong and get out-of-date. It's not worth the trouble if you don't really need it.


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

Need Your Help

How can I create memory dumps and analyze memory leaks?

c++ memory-leaks

I need to get the following to analyze a memory leak issue. How to do that?

Unwanted one clock delay vhdl

vhdl fpga fifo vlsi

can someone explain me why I have one clock delay on my simulation of the following and how can I fix it, it shouldnt be there cause I am missing a bit on the output....