paper_trail gem saving versions with object_changes nil
Asked Answered
R

2

5

We just started using the PaperTrail gem and have noticed that 75% of the records in the versions table have nil for the object_changes column. Any idea why this would be happening and how we can stop it?

Using Rails 5.1 and PaperTrail 10.1.

Receptionist answered 20/2, 2019 at 14:31 Comment(0)
R
3

The nil object changes is due to touch events on attributes that were skipped. The only solution I came up with for that is to only track versions on create, update and destroy.

I also discovered that we had duplicate version records. We turned on PaperTrail for all models by putting the below in ApplicationRecord, this caused duplicate versions to be created if a class inherited from another one. ie If you have class Foo < Bar and do Bar.create that would create 2 identical version records.

Initial Version in ApplicationRecord

def self.inherited(subclass)
  super
  subclass.send(:has_paper_trail)
end

Final Version

def self.inherited(subclass)
  classes_to_skip = %w[Foo]
  attributes_to_skip = [:bar_at]
  on_actions = [:create, :update, :destroy]

  super
  unless classes_to_skip.include?(subclass.name)
    subclass.send(:has_paper_trail, on: on_actions, ignore: attributes_to_skip)
  end
end
Receptionist answered 21/2, 2019 at 18:5 Comment(0)
O
10

Building up on @Scott's answer, create an initializer and set PaperTrail's global config (version 10+ only) to ignore the :touch events.

This was creating millions of needless versions in our database.

config/initializers/paper_trail.rb

PaperTrail.config.has_paper_trail_defaults = {
  on: %i[create update destroy]
}
Osteology answered 26/11, 2019 at 14:15 Comment(1)
This should be marked as the accepted answer. It is easy to implement and works flawless.Coherence
R
3

The nil object changes is due to touch events on attributes that were skipped. The only solution I came up with for that is to only track versions on create, update and destroy.

I also discovered that we had duplicate version records. We turned on PaperTrail for all models by putting the below in ApplicationRecord, this caused duplicate versions to be created if a class inherited from another one. ie If you have class Foo < Bar and do Bar.create that would create 2 identical version records.

Initial Version in ApplicationRecord

def self.inherited(subclass)
  super
  subclass.send(:has_paper_trail)
end

Final Version

def self.inherited(subclass)
  classes_to_skip = %w[Foo]
  attributes_to_skip = [:bar_at]
  on_actions = [:create, :update, :destroy]

  super
  unless classes_to_skip.include?(subclass.name)
    subclass.send(:has_paper_trail, on: on_actions, ignore: attributes_to_skip)
  end
end
Receptionist answered 21/2, 2019 at 18:5 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.