Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Provide a way to rebuild data with missing create audit #681

Draft
wants to merge 2 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 16 additions & 2 deletions lib/audited/audit.rb
Original file line number Diff line number Diff line change
Expand Up @@ -61,11 +61,16 @@ class Audit < ::ActiveRecord::Base
scope :from_version, ->(version) { where("version >= ?", version) }
scope :to_version, ->(version) { where("version <= ?", version) }
scope :auditable_finder, ->(auditable_id, auditable_type) { where(auditable_id: auditable_id, auditable_type: auditable_type) }
# Return all audits older than the current one.
# Return all audits older than and the current one.
def ancestors
self.class.ascending.auditable_finder(auditable_id, auditable_type).to_version(version)
end

# Returns all the audits younger than and the current one.
def descendants
self.class.ascending.auditable_finder(auditable_id, auditable_type).from_version(version)
end

# Return an instance of what the object looked like at this revision. If
# the object has been destroyed, this will be a new record.
def revision
Expand Down Expand Up @@ -143,10 +148,19 @@ def self.as_user(user)

# @private
def self.reconstruct_attributes(audits)
audits.each_with_object({}) do |audit, all|
previous_attributes = audits.each_with_object({}) do |audit, all|
all.merge!(audit.new_attributes)
all[:audit_version] = audit.version
end

unless audits.empty? || audits.first.action == "create"
later_attributes = audits.last.descendants.each_with_object({}) do |audit, all|
all.merge!(audit.old_attributes)
end
return later_attributes.merge(previous_attributes)
end

previous_attributes
end

# @private
Expand Down
5 changes: 5 additions & 0 deletions lib/audited/auditor.rb
Original file line number Diff line number Diff line change
Expand Up @@ -415,6 +415,11 @@ def run_conditional_check(condition, matching: true)

def reconstruct_attributes(audits)
attributes = {}

unless audits.present? && self.audits.creates.any?
self.audits.each { |audit| attributes.merge!(audit.old_attributes) }
end

audits.each { |audit| attributes.merge!(audit.new_attributes) }
attributes
end
Expand Down