diff --git a/README.md b/README.md index d17ede9b..c943cc5c 100644 --- a/README.md +++ b/README.md @@ -614,12 +614,14 @@ The best way to diff adjacent versions is to get PaperTrail to do it for you. I ```ruby >> widget = Widget.create :name => 'Bob' ->> widget.versions.last.changeset # {} +>> widget.versions.last.changeset # {'name' => [nil, 'Bob']} >> widget.update_attributes :name => 'Robert' >> widget.versions.last.changeset # {'name' => ['Bob', 'Robert']} +>> widget.destroy +>> widget.versions.last.changeset # {} ``` -Note PaperTrail only stores the changes for updates; there's no point storing them for created or destroyed objects. +Note PaperTrail only stores the changes for creation and updates; it doesn't store anything when an object is destroyed. Please be aware that PaperTrail doesn't use diffs internally. When I designed PaperTrail I wanted simplicity and robustness so I decided to make each version of an object self-contained. A version stores all of its object's data, not a diff from the previous version. This means you can delete any version without affecting any other. diff --git a/lib/paper_trail/has_paper_trail.rb b/lib/paper_trail/has_paper_trail.rb index a98b36a1..153ec726 100644 --- a/lib/paper_trail/has_paper_trail.rb +++ b/lib/paper_trail/has_paper_trail.rb @@ -149,7 +149,17 @@ module PaperTrail def record_create if switched_on? - send(self.class.versions_association_name).create merge_metadata(:event => 'create', :whodunnit => PaperTrail.whodunnit) + data = { + :event => 'create', + :whodunnit => PaperTrail.whodunnit + } + + if changed_notably? and version_class.column_names.include?('object_changes') + # The double negative (reject, !include?) preserves the hash structure of self.changes. + data[:object_changes] = self.changes.reject { |k, _| !notably_changed.include?(k) }.to_yaml + end + + send(self.class.versions_association_name).create merge_metadata(data) end end diff --git a/test/unit/model_test.rb b/test/unit/model_test.rb index daa1e9f6..485005eb 100644 --- a/test/unit/model_test.rb +++ b/test/unit/model_test.rb @@ -143,12 +143,19 @@ class HasPaperTrailModelTest < ActiveSupport::TestCase assert @widget.live? end - should 'not have changes' do - assert_equal Hash.new, @widget.versions.last.changeset + should 'have changes' do + changes = { + 'name' => [nil, 'Henry'], + 'created_at' => [nil, @widget.created_at], + 'updated_at' => [nil, @widget.updated_at], + 'id' => [nil, 1] + } + + assert_equal changes, @widget.versions.last.changeset end context 'and then updated without any changes' do - setup { @widget.save } + setup { @widget.touch } should 'not have a new version' do assert_equal 1, @widget.versions.length