在 Paper Trail gem 的版本模型上添加一个 counter_cache 列

Adding a counter_cache column on the version model for the Paper Trail gem

我有一个配置了 PT 的 Page 模型。我还有一个 Versions::PageVersion 模型,因为页面版本存储在单独的 table (page_versions) 中。 Page 模型有一个用于计数器缓存的列,称为 page_versions_count。到目前为止,一切都很标准。

为了使计数器缓存工作,我覆盖了版本模型上的 belongs_to :item 关联,如下所示:

class Versions::PageVersion < PaperTrail::Version
  belongs_to :item,
             polymorphic: true,
             counter_cache: true
end

这确实有效,但我现在想知道这是否是正确的方法。

PT 不提供配置 belongs_to :item 关联的方法。关联选项硬编码在 paper_trail/version_concern.rb:18.

AFAICT,像你这样重新定义一个关联,是AR支持的。新选项(包括 counter_cache)替换(而不是合并)旧选项。我已经使用 ActiveRecord::Reflection 实验性地证实了这一点,但找不到承认这一点的官方文档。

所以,你的解决方案是我能想到的最好的。

如果您想为文档贡献您的解决方案,我很乐意查看 PR。我建议在“5.b.配置版本关联”部分附近的某个地方。