从大于 0 开始计数器缓存

Starting a counter cache from greater than 0

我有 has_many 对象的记录。这些对象已在 record_id 列中创建,并预先填充了未来的 record.id。但是,当创建该未来记录时,计数器缓存始终从 0 开始。

如何使计数器缓存从正确数量的关联对象而不是零开始?

您可能正在寻找 reset_counters。来自文档:

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)