Search code examples
ruby-on-railsactiverecordpaper-trail-gem

Apply PaperTrail to all models


I don't think there is an easy way to apply PaperTrail to all model except by declaring has_paper_trail in each one. What I want to accomplish is to leverage the features of PaperTrail (or another gem, like Auditable, Vestal Versions) to all the models. For example, I want to include models generated by gems and engines (Rails 3).

Any pointers on how to apply a "global" PaperTrail (or similar gem)?


Solution

  • For Rails 5.0+ (if app has the ApplicationRecord class)

    class ApplicationRecord < ActiveRecord::Base
      def self.inherited subclass
        super
        subclass.send(:has_paper_trail)
      end
    end
    

    For older Rails versions

    # config/initializers/paper_trail_extension.rb 
    ActiveRecord::Base.singleton_class.prepend Module.new {
      def inherited subclass
        super
        skipped_models = ["ActiveRecord::SchemaMigration", "PaperTrail::Version", "ActiveRecord::SessionStore::Session"]
        unless skipped_models.include?(subclass.to_s)
          subclass.send(:has_paper_trail)
        end
      end
    }
    

    (It is important that you use {/} and not do/end after Module.new because of operator precedence).