paper-trail-gem

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


I have a Page model with PT configured. I also have a Versions::PageVersion model because page versions are stored in a separate table (page_versions). The Page model has a column for counter cache, called page_versions_count. So far, everything is pretty standard.

To make the counter cache work, I've overwritten the belongs_to :item association on the version model, which looks as follows:

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

This actually works, but I'm wondering now if that's the right way to do it.


Solution

  • PT does not provide a way to configure the belongs_to :item association. The association options are hard-coded in paper_trail/version_concern.rb:18.

    AFAICT, re-defining an association, as you have done, is supported by AR. The new options (including counter_cache) replace (rather than merge with) the old options. I've confirmed this experimentally using ActiveRecord::Reflection, but can't find official docs acknowledging this.

    So, your solution is the best that I can think of.

    If you'd like to contribute your solution to the docs, I'd happily review a PR. I'd suggest somewhere near section "5.b. Configuring the versions Association".