diff --git a/lib/audited/audit.rb b/lib/audited/audit.rb index 7201adac..eee21b70 100644 --- a/lib/audited/audit.rb +++ b/lib/audited/audit.rb @@ -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 @@ -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 diff --git a/lib/audited/auditor.rb b/lib/audited/auditor.rb index 48da81bd..8a543708 100644 --- a/lib/audited/auditor.rb +++ b/lib/audited/auditor.rb @@ -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