From 5ca65b8a357e77ad30fcec23a275d4b512226d95 Mon Sep 17 00:00:00 2001 From: "Jasper St. Pierre" Date: Thu, 18 Jan 2024 11:13:52 -0500 Subject: [PATCH] fix: normalize enum changes before filtering duplicate audits on touch --- lib/audited/auditor.rb | 3 ++- spec/audited/auditor_spec.rb | 8 ++++++++ spec/support/active_record/models.rb | 1 + 3 files changed, 11 insertions(+), 1 deletion(-) diff --git a/lib/audited/auditor.rb b/lib/audited/auditor.rb index 9fd90092..e2f1388e 100644 --- a/lib/audited/auditor.rb +++ b/lib/audited/auditor.rb @@ -249,6 +249,8 @@ def audited_changes(for_touch: false, exclude_readonly_attrs: false) all_changes.except(*self.class.non_audited_columns) end + filtered_changes = normalize_enum_changes(filtered_changes) + if for_touch && (last_audit = audits.last&.audited_changes) filtered_changes.reject! do |k, v| last_audit[k].to_json == v.to_json || @@ -258,7 +260,6 @@ def audited_changes(for_touch: false, exclude_readonly_attrs: false) filtered_changes = redact_values(filtered_changes) filtered_changes = filter_encrypted_attrs(filtered_changes) - filtered_changes = normalize_enum_changes(filtered_changes) filtered_changes.to_hash end diff --git a/spec/audited/auditor_spec.rb b/spec/audited/auditor_spec.rb index 72f71fa0..a8af7bcb 100644 --- a/spec/audited/auditor_spec.rb +++ b/spec/audited/auditor_spec.rb @@ -540,6 +540,14 @@ class CallbacksSpecified < ::ActiveRecord::Base expect(user.audits.last.action).to eq("update") expect(user.audits.last.audited_changes.keys).to eq(%w[suspended_at]) end + + it "updating nested resource through parent while changing an enum on parent shouldn't double audit" do + user.status = :reliable + user.companies_attributes = [{name: "test"}] + expect { user.save }.to change(user.audits, :count).from(1).to(2) + expect(user.audits.last.action).to eq("update") + expect(user.audits.last.audited_changes.keys).to eq(%w[status]) + end end context "after updating" do diff --git a/spec/support/active_record/models.rb b/spec/support/active_record/models.rb index 6e50b552..2922afe4 100644 --- a/spec/support/active_record/models.rb +++ b/spec/support/active_record/models.rb @@ -136,6 +136,7 @@ class Owner < ::ActiveRecord::Base has_associated_audits has_many :companies, class_name: "OwnedCompany", dependent: :destroy accepts_nested_attributes_for :companies + enum status: {active: 0, reliable: 1, banned: 2} end class OwnedCompany < ::ActiveRecord::Base