問題描述
從大於 0 開始計數器緩存 (Starting a counter cache from greater than 0)
我有包含多個對象的記錄。已經使用預先填充了未來 record.id 的 record_id 列創建了對象。但是,當創建未來的記錄時,計數器緩存始終從 0 開始。
如何使計數器緩存從正確數量的關聯對象而不是零開始?
參考解法
方法 1:
You are probably looking for the reset_counters
. From the docs:
Resets one or more counter caches to their correct value using an SQL count query. This is useful when adding new counter caches, or if the counter has been corrupted or modified directly by SQL.
Example:
# For the Post with id #1, reset the comments_count Post.reset_counters(1, :comments)
(by ecki、spickermann)