:counter_cache =>true 用于存储总和 [英] :counter_cache => true for storing sum

查看:46
本文介绍了:counter_cache =>true 用于存储总和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有usersscores 表.以下是关联:

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

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

users 有名为 scores_count 的列.在此列中,我将所有值的总和存储在 scores 表中.

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

我想用这种方式将所有 scores 的总和存储在 scores_count::counter_cache =>真实

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

但是 :counter_cache =>true 只保存表 scores 中的行数.是否有任何类似的方法来存储表 scores 中所有值的总和?还是这个任务要我自己来实现?

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?

推荐答案

没有.你必须自己实现它.计数器缓存仅用于存储关联记录的数量.您可以使用 Score 上的回调来实现它,以更新关联的 User.另请参阅如何在 rails 中缓存计算列?

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.

这篇关于:counter_cache =>true 用于存储总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆